简体   繁体   中英

C# / VB.Net Task vs Thread vs BackgroundWorker

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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