C# / VB.Net Task vs Thread vs BackgroundWorker

眉间皱痕 提交于 2019-12-22 05:06:38

问题


I have "Googled" but still confused with Task, Thread, and Background Worker.....

  1. Is "Task is a high level API that running on current thread" correct ?

  2. If 1 is correct, why I need to use invoke to change the UI inside the task at same thread ?

  3. Backgroundworker only got lowest priority in the application ? So the performance of backgroundworker is lower than task and thread ? Right ?

  4. Finally, in my application I need to get a string from server using "HttpWebRequest", after that parse the string and update the UI. If I use "HttpWebRequest.BeginGetResponse" to wait for the async result and trigger an complete event to update the UI, I need to use invoke method to call the UI thread control, but can I use background worker instead of ? I can just simply change the UI in "RunWorkerCompleted" event, are there any disadvantage ?

Sorry for my pool English and thanks for help...!


回答1:


1) No, a Task is by default run on a thread pool thread. You can provide another scheduler which can run tasks differently, though.

3) There is no difference in priority by default. BackgroundWorker also runs on a thread pool thread.

4) Using TaskFactory.FromAsync is a rather simple way to handle asynchronous web requests:

Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
    .ContinueWith(
        t =>
        {
            using (var response = (HttpWebResponse)t.Result)
            {
                // Do your work
            }
        },
        TaskScheduler.FromCurrentSynchronizationContext()
    );

Using TaskScheduler.FromCurrentSynchronizationContext ensures that the callback in ContinueWith is invoked on the current thread. So, if the task is created on the UI thread, the response will be retrieved in the background and then processed on the UI thread.



来源:https://stackoverflow.com/questions/12483229/c-sharp-vb-net-task-vs-thread-vs-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!