I have this code for execute httpwebrequest and response in background method and i just want show dialog for information when download zip crashed and my code enter in this catch...
private void DoSincroFit()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
}
public async void playResponseAsync(IAsyncResult asyncResult)
{
//Declaration of variables
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
try
{
string fileName = "sincrofit.rar";
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
byte[] buffer = new byte[1024];
var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
var newZipFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = writeStream.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outputStream))
{
using (Stream input = webResponse.GetResponseStream())
{
var totalSize = 0;
for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
{
dataWriter.WriteBytes(buffer);
totalSize += size; //get the progress of download
}
await dataWriter.StoreAsync();
await outputStream.FlushAsync();
dataWriter.DetachStream();
}
}
}
}
}
}
catch
{
SMethods.Message_Dialog("Download has stopped!","Error");
}
}
But when my code execute this method, from this class:
class StandarMethods
{
public async void Message_Dialog(string text, string title)
{
//Declaration of variables
MessageDialog MDialog = new MessageDialog(text, title);
await MDialog.ShowAsync();
}
}
Finally my app crash when try to execute:
await MDialog.ShowAsync();
This await in background task... Someone can helps me? It's possible time to use Event Handlers? Why? How? Thanks in advance!
Solved, and my final code is here:
Thanks for your time @loop!
Merli your problem is you are trying to access the UI thread from a background tread to show dialog to user So use Dispatcher for this Basic example is : -
For winrt part -
My final code:
This is my photo:
Thanks for all!