[英]C# / VB.Net Task vs Thread vs BackgroundWorker
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 ? “任务是在当前线程上运行的高级API”是否正确?
If 1 is correct, why I need to use invoke to change the UI inside the task at same thread ? 如果1是正确的,为什么我需要使用invoke来更改同一线程中任务内的UI?
Backgroundworker only got lowest priority in the application ? Backgroundworker在应用程序中只获得最低优先级? So the performance of backgroundworker is lower than task and thread ?
那么backgroundworker的性能低于任务和线程? Right ?
对 ?
Finally, in my application I need to get a string from server using "HttpWebRequest", after that parse the string and update the UI. 最后,在我的应用程序中,我需要使用“HttpWebRequest”从服务器获取一个字符串,之后解析字符串并更新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 ?
如果我使用“HttpWebRequest.BeginGetResponse”来等待异步结果并触发一个完整的事件来更新UI,我需要使用invoke方法来调用UI线程控件,但是我可以使用后台工作器代替吗? I can just simply change the UI in "RunWorkerCompleted" event, are there any disadvantage ?
我可以简单地在“RunWorkerCompleted”事件中更改UI,有什么不利之处吗?
Sorry for my pool English and thanks for help...! 对不起我的游泳池英语并感谢您的帮助......!
1) No, a Task is by default run on a thread pool thread. 1)否,默认情况下,任务在线程池线程上运行。 You can provide another scheduler which can run tasks differently, though.
但是,您可以提供另一个可以以不同方式运行任务的调度程序。
3) There is no difference in priority by default. 3)默认优先级没有差异。
BackgroundWorker
also runs on a thread pool thread. BackgroundWorker
还在线程池线程上运行。
4) Using TaskFactory.FromAsync
is a rather simple way to handle asynchronous web requests: 4)使用
TaskFactory.FromAsync
是处理异步Web请求的一种相当简单的方法:
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. 使用
TaskScheduler.FromCurrentSynchronizationContext
可确保在当前线程上调用ContinueWith
中的回调。 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. 因此,如果在UI线程上创建任务,则将在后台检索响应,然后在UI线程上处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.