Reputation: 640
I am working in windows phone 8. I am trying to save multiple images to isolated storage. But at the time of saving it's like my UI is being hanged. May be this is happening for "Deployment.Current.Dispatcher.BeginInvoke". If i don't use Deployment.Current.Dispatcher.BeginInvoke then I get an Invalid cross-thread access error at the line "var bi = new BitmapImage();".
Sample code for saving images:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var workingDictionary = new Dictionary<string, Stream>(streamDictionary);
foreach (var item in workingDictionary)
{
var isoStore = IsolatedStorageFile.GetUserStoreForApplication();
if (isoStore.FileExists(item.Key))
isoStore.DeleteFile(item.Key);
using (var writer = new StreamWriter(new IsolatedStorageFileStream(item.Key, FileMode.Create, FileAccess.Write, isoStore)))
{
var encoder = new PngEncoder();
var bi = new BitmapImage();
bi.SetSource(item.Value);
var wb = new WriteableBitmap(bi);
encoder.Encode(wb.ToImage(), writer.BaseStream);
System.Diagnostics.Debug.WriteLine("saving..." + item.Key);
}
}
});
Any help will be highly appreciated.
Upvotes: 1
Views: 171
Reputation: 9242
Your UI will definitly freeze the reason behind this is.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// This code run on UI thread..
}
This code basically run the code inside it on the UI thead.
Just put the inside code in some other async Task something like that..
private async Task RunInBackgroud()
{
await Task.Run(()=>{}); // This is because any async Task does not went to background until
// it encounter first await. this is just to make the thread in backgound as fast as possible.
// your code for saving files..
..
..
}
and the call the above as a simple method call. Hope it help you.
EDIT :- Why not just put this bitmap creation in Dispatcher code.
like..
BitmapImage bi;
Dispatcher.BeginInvoke(() => {
bi = new BitmapImage();
});
EDIT 2 :- Here are some reference for the similar problem..
Creating BitmapImage on background thread WP7
Invalid cross-thread access issue
Upvotes: 1
Reputation: 38
You cannot access the UI thread from any other thread directly. So, Encose your UI access code in the Dispatcher.BeginInvoke()
Dispatcher.BeginInvoke(() =>
{
foreach (Button i in bts)
i.Content = "";
});
Or else please go through this link:
http://www.codeproject.com/Articles/368983/Invoking-through-the-Dispatcher-on-Windows-Phone-a
Upvotes: 0
Reputation: 418
I'm not familiar with windows phone programming, but it sounds like a threading issue. In Windows both actions would be done on the same thread. This is why the UI can't be updated at the same time but only after the save action.
Maybe this is the same for Windows Phone?
Upvotes: 0