简体   繁体   English

UI阻止了HttpWebRequest回调

[英]HttpWebRequest callback is blocked by UI

EDITED: On Windows Phone I am calling HttpWebRequest.BeginGetResponse on a separate thread that I started. 编辑:在Windows Phone上我在一个单独的线程上调用HttpWebRequest.BeginGetResponse Then I call MessageBox.Show(). 然后我调用MessageBox.Show()。 The problem is that the callback is not called until I dismiss the MessageBox. 问题是在我解除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();

Should the MessageBox be blocking the callback on the background thread? MessageBox是否应阻止后台线程上的回调?

Need to add a reference to Microsoft.Phone.Reactive 需要添加对Microsoft.Phone.Reactive的引用

Try this: 尝试这个:

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)
        {

        }

"MessageBox.Show();" “MessageBox.Show();” will block your ui thread . 将阻止你的ui线程。

but i don't think it is the reason the GetResponseCallback does not run. 但我不认为这是GetResponseCallback不运行的原因。

you can test it , comment that code. 你可以测试它,评论该代码。

if you want to use MessageBox.Show(); 如果你想使用MessageBox.Show();

then place a this inside dispacher 然后把它放在调度员里面

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM