问题
I have "Googled" but still confused with Task, Thread, and Background Worker.....
Is "Task is a high level API that running on current thread" correct ?
If 1 is correct, why I need to use invoke to change the UI inside the task at same thread ?
Backgroundworker only got lowest priority in the application ? So the performance of backgroundworker is lower than task and thread ? Right ?
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