何时使用Task.Run,​​何时使用异步等待以及何时结合使用它们 [英] When to use Task.Run, when to use async- await and when to use them in combination

查看:77
本文介绍了何时使用Task.Run,​​何时使用异步等待以及何时结合使用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多帖子,但仍然无法区分所有这些帖子.我所能理解的只是Task.Run将调用后台线程.async-wait是异步编程.

I have read many posts but still unable to differentiate between all these. All i could understand was Task.Run will call the background thread. async- await is asynchronous programming.

Task.Run是否意味着后台线程将充当阻塞线程?

Does Task.Run means background thread will behave as a blocking thread?

尝试从Internet下载多个大图像.我应该如何结合使用这些关键字,为什么?

Trying to download multiple large images from internet. How should i use these keywords in combination and why?

推荐答案

何时使用Task.Run,​​何时使用异步等待以及何时将其组合使用

When to use Task.Run, when to use async- await and when to use them in combination

我有一个关于该主题的整个博客系列,但总而言之:

I have an entire blog series on the subject, but in summary:

  • 对于具有UI的应用程序,使用 Task.Run 将CPU绑定(或阻止)工作移出UI线程.
  • 使用 async / await 进行I/O绑定工作.
  • Use Task.Run to move CPU-bound (or blocking) work off of the UI thread for apps with a UI.
  • Use async/await for I/O-bound work.

在其他一些罕见的情况下,使用 Task.Run async 很有用,但是以上两点为大多数情况提供了指导.

There are some more rare cases where Task.Run or async can be useful, but the two points above provide guidance for most situations.

Task.Run是否意味着后台线程将充当阻塞线程?

Does Task.Run means background thread will behave as a blocking thread?

Task.Run 实际上可以同步或异步运行,但是它确实使用线程池线程.

Task.Run can actually run synchronously or asynchronously, but it does use thread pool threads.

我正在尝试在.net 4.5中创建桌面控制台应用程序

i am trying to create a desktop console application in .net 4.5

尝试从Internet下载多个大图像.我应该如何结合使用这些关键字,为什么?

Trying to download multiple large images from internet. How should i use these keywords in combination and why?

这是非UI应用程序中受I/O约束的操作,因此,您绝对应该首选 async / await .

This is an I/O-bound operation in a non-UI app, so you should definitely prefer async/await.

这篇关于何时使用Task.Run,​​何时使用异步等待以及何时结合使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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