C#中的异步/等待和并行 [英] Async/await and parallel in C#

查看:191
本文介绍了C#中的异步/等待和并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应在C#中使用async/await,何时应使用parallel.foreach?并行和异步/等待是否达到相同的目的? 它们有什么区别?

When should I use async/await and when should I use parallel.foreach in C#? Are parallel and async/await serve the same purpose? What are the differences in them?

推荐答案

异步/等待与异步有关,而Parallel.ForEach并行性有关.它们是相关的概念,但并不相同.

async/await is about asynchrony, whereas Parallel.ForEach is about parallelism. They're related concepts, but not the same.

Parallel.ForEach用于当您要对集合中的所有项目并行执行相同的操作时,阻塞当前线程,直到所有操作完成.

Parallel.ForEach is used when you want to execute the same operation on all the items in a collection, in parallel, blocking the current thread until all operations have completed.

async/await用于在特定异步操作完成之前当前操作无法进行任何操作,但又不想阻塞当前线程的情况.这在两种情况下特别有用:

async/await is used when the current operation can't make any more progress until a particular asynchronous operation has completed, but you don't want to block the current thread. This is particularly useful in two situations:

  • 基本上在UI线程上一个接一个地启动各种异步操作的编写代码,在两次操作之间短暂地访问UI. (比这更笼统,但这是一个简单的示例.)您不想阻塞UI线程,但是管理所有这些异步操作则很痛苦.
  • 一次
  • 一次处理很多长时间运行的操作-例如在Web服务器中.由于调用其他Web服务,数据库等,每个单独的请求可能会花费很长时间-但您不希望每个请求都有一个线程,因为线程是一种相对昂贵的资源.
  • Writing code which basically kicks off various asynchronous operations, one after the other, on the UI thread, accessing the UI briefly between operations. (It's more general than that, but that's a simple example.) You don't want to block the UI thread, but managing all of those asynchronous operations is a pain otherwise.
  • Handling lots of long-running operations at a time - e.g. in a web server. Each individual request may take a long time due to calling into other web service, databases etc - but you don't want to have one thread per request, as threads are a relatively expensive resource.

您可以通过启动一个将调用Parallel.ForEach的新任务,然后等待该任务来结合并行性和异步性. (仅举一个例子.)

You can combine parallelism and asynchrony by kicking off a new task which will call Parallel.ForEach, and then awaiting that task. (Just as one example.)

这篇关于C#中的异步/等待和并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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