AsyncCallback之后的异常

时间:2012-11-15 01:03:11

标签: c# .net httpwebrequest asynccallback

我遇到AsyncCallback函数问题。我正在使用一个来下载数据,然后在我之后做的任何事情都会引发一个不同的异常。一些代码:

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");
}

有没有办法告诉异步回调何时完成,然后运行代码而不会崩溃,或者我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

问题是你从线程池线程调用MessageBox.Show。您需要从UI线程调用它。为此,您需要与UI线程同步。例如:

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

Invoke的调用将执行UI线程上的代码。有关详细信息,请参阅Control.Invoke的文档。