Execute a WebRequest in a Background thread while UI Thread is blocked

后端 未结 2 1123
暖寄归人
暖寄归人 2021-01-25 03:37

Why does the following code executes WebRequests after 5 secs when the UI Thread isn\'t being blocked anymore? Thread.Sleep is in the UI Thread while both Instantia

2条回答
  •  无人共我
    2021-01-25 04:06

    Maybe you mean to do this instead:

    Loaded += (sender, args) =>
    {
        ThreadPool.QueueUserWorkItem(dummy =>
        {
            for (int i = 0; i < 5; i++)
            {
    
                ThreadPool.QueueUserWorkItem(state =>
                {
                    var request = WebRequest.CreateHttp("http://google.com");
                    request.BeginGetResponse(ar => Debug.WriteLine("Request finished"), null);
                });
    
                Thread.Sleep(1000);
            }
        });
    
    };
    

    This doesn't block the UI at all and the Debug message is coming every second. Or what would be your desired behavior? Do you really want to block the UI (you shouldn't...)?

    EDIT (after your edit):

    I see. That's kind of counter-intuitive and I don't have an answer right away. I strongly suspect the request requires some UI thread activity. Your main thread should always be responsive and never block so this would be no problem. Unless you block the main thread. So they might have spared themselves the work to optimize for the flawed case (which this is).

    Nevertheless the answer would be interesting. I know from the desktop world that browser related stuff needs the main thread. So I recommend not blocking it anymore :)

提交回复
热议问题