Question

I'm having problems with an AsyncCallback function. I'm using one to download data, and then whatever I do after that, it throws a different exception. Some code:

private void downloadBtn_Click(object sender, RoutedEventArgs e)
{
    string fileName = System.IO.Path.GetFileName(Globals.CURRENT_PODCAST.Title.Replace(" ", string.Empty));
    MessageBox.Show("Download is starting");
    file = IsolatedStorageFile.GetUserStoreForApplication();
    streamToWriteTo = new IsolatedStorageFileStream(fileName, FileMode.Create, file);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(Globals.CURRENT_PODCAST.Uri));
    request.AllowReadStreamBuffering = false;
    request.BeginGetResponse(new AsyncCallback(GetData), request);
}

private void GetData(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
    Stream str = response.GetResponseStream();
    byte[] data = new byte[16* 1024];
    long totalValue = response.ContentLength;
    while (str.Read(data, 0, data.Length) > 0)
    {
        if (streamToWriteTo.CanWrite)
            streamToWriteTo.Write(data, 0, data.Length);
        else
            MessageBox.Show("Could not write to stream");
    }
    streamToWriteTo.Close();
    MessageBox.Show("Download Finished");
}

Is there any way to tell when an async callback has finished, and then run code without crashing, or something I am doing wrong here?

Was it helpful?

Solution

The problem is that you're calling MessageBox.Show from a threadpool thread. You need to call it from the UI thread. To do that, you need to synchronize with the UI thread. For example:

this.Invoke((MethodInvoker) delegate
    { MessageBox.Show("success!"); });

The call to Invoke will execute the code on the UI thread. See documentation for Control.Invoke for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top