Hi
Basically i'm using msft's sample code SMS background task sample and add the Save function(every time sms received, save it to local file) in the run method in SampleSmsBackgroundTask.cs
It works fine, but every 1 out of 5, i got this exception:A concurrent or interleaved operation changed the state of the object, invalidating this operation. (Exception from HRESULT: 0x8000000C). In what circumstances will this E_CHANGED_STATE
exception happened?
I caught this exception in my Save function
Here is my code snippet
public async void Save(IBackgroundTaskInstance taskInstance)
{
//get the storage for your app
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile timeOrderFile = await localFolder.CreateFileAsync("output.txt", CreationCollisionOption.OpenIfExists);
string output = await FileIO.ReadTextAsync(timeOrderFile);
output+="bachground is on.\n";
SmsReceivedEventDetails smsDetails = (SmsReceivedEventDetails)taskInstance.TriggerDetails;
try
{
SmsDevice smsDevice = (SmsDevice)await SmsDevice.FromIdAsync(smsDetails.DeviceId);
SmsBinaryMessage smsEncodedmsg = (SmsBinaryMessage)await smsDevice.MessageStore.GetMessageAsync(smsDetails.MessageIndex);
SmsTextMessage smsTextMessage = Windows.Devices.Sms.SmsTextMessage.FromBinaryMessage(smsEncodedmsg);
output+=smsTextMessage.Body+" "+" "+smsTextMessage.From+" "+smsTextMessage.Timestamp+"\r\n";
}
catch (Exception e)
{
output +="error="+e.Message+"\r\n";
}
await FileIO.WriteTextAsync(timeOrderFile, output);
}
public async void Run(IBackgroundTaskInstance taskInstance)
{
//
// Associate a cancellation handler with the background task.
//
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
//
// Do the background task activity.
//
Save(taskInstance);
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
await DisplayToastAsync(taskInstance);
//
// Provide status to application via local settings storage
//
var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
settings.Values[taskInstance.Task.TaskId.ToString()] = "Completed";
Debug.WriteLine("Background " + taskInstance.Task.Name + ("process ran"));
deferral.Complete();
}