C# / VB.Net Task vs Thread vs BackgroundWorker

拜拜、爱过 提交于 2019-12-05 04:28:37

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.

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