C#/ VB.Net任务VS主题VS的BackgroundWorker [英] C# / VB.Net Task vs Thread vs BackgroundWorker

查看:334
本文介绍了C#/ VB.Net任务VS主题VS的BackgroundWorker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我Googled了,但还是有疑惑的任务,线程和后台工作.....

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


  1. 是任务是,在当前线程运行的高层次的API是否正确?

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

如果1是正确的,为什么我需要使用调用来改变里面的UI在同一个线程任务?

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

BackgroundWorker的应用程序中只拿到最低的优先级?这样的BackgroundWorker的性能比任务和线程低?对吗?

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

最后,在我的应用程序需要使用从服务器获取一个字符串HttpWebRequest的,之后解析字符串并更新UI。
如果我使用HttpWebRequest.BeginGetResponse等待异步结果,并触发一个完整的事件更新UI,我需要使用invoke方法来调用UI线程控制,但我可以用后台工作,而不是?我可以简单地改变UI中的RunWorkerCompleted事件,有什么劣势?

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)默认情况下优先无差异。 的BackgroundWorker 也运行在一个线程池线程。

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

4)使用 TaskFactory.FromAsync 是一个相当简单的方法来处理异步Web请求:

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()
    );

使用 TaskScheduler.FromCurrentSynchronizationContext 确保回调在 ContinueWith 调用当前线程上。因此,如果在UI线程上创建任务,响应将在后台检索,然后在UI线程上处理。

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.

这篇关于C#/ VB.Net任务VS主题VS的BackgroundWorker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆