UI阻止了HttpWebRequest回调

时间:2012-10-12 11:26:05

标签: c# windows-phone-7

已编辑:在Windows Phone上,我在一个单独的线程上调用HttpWebRequest.BeginGetResponse 我已开始。然后我调用MessageBox.Show()。问题是在我解除MessageBox之前不会调用回调。

void GetResponseCallback(IAsyncResult asynchronousResult) {
    //Not getting called until I dismiss MessageBox
}

void getWeb() {
    Thread.Sleep(1000);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
    request.Method = "GET";
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

new Thread(getWeb).Start(); //Start a new thread
MessageBox.Show();

MessageBox是否应阻止后台线程上的回调?

3 个答案:

答案 0 :(得分:0)

需要添加对Microsoft.Phone.Reactive

的引用

试试这个:

private void PushMe_Click(object sender, RoutedEventArgs e)
        {
            var scheduler = Scheduler.NewThread;
            scheduler.Schedule(action => GetWeb());         
            MessageBox.Show("This is a test.", "Test caption.", MessageBoxButton.OK);
        }

        private void GetWeb()
        {
            Thread.Sleep(3000);
            var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.stackoverflow.com");
            httpWebRequest.Method = "GET";

            httpWebRequest.BeginGetResponse(BeginGetResponseCallback, httpWebRequest);
        }

        private void BeginGetResponseCallback(IAsyncResult ar)
        {

        }

答案 1 :(得分:0)

“MessageBox.Show();”将阻止你的ui线程。

但我不认为这是GetResponseCallback不运行的原因。

你可以测试它,评论那段代码。

答案 2 :(得分:0)

如果您想使用MessageBox.Show();

然后将其放入调度员

void GetResponseCallback(IAsyncResult asynchronousResult) 
{
    Dispatcher.BeginInvoke(() =>
    {
        MessageBox.Show("Done");
    });

}

void getWeb() {
    Thread.Sleep(1000);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
    request.Method = "GET";
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

new Thread(getWeb).Start(); //Start a new thread