我认为它们基本上是相同的 - 编写在处理器之间分割任务的程序(在具有2个以上处理器的机器上).然后我正在阅读https://msdn.microsoft.com/en-us/library/hh191443.aspx,其中说
异步方法旨在实现非阻塞操作.异步方法中的await表达式在等待的任务运行时不会阻止当前线程.相反,表达式将方法的其余部分作为延续进行注册,并将控制权返回给异步方法的调用者.
async和await关键字不会导致创建其他线程.异步方法不需要多线程,因为异步方法不能在自己的线程上运行.该方法在当前同步上下文上运行,并仅在方法处于活动状态时在线程上使用时间.您可以使用Task.Run将CPU绑定的工作移动到后台线程,但后台线程无助于正在等待结果可用的进程.
我想知道是否有人可以为我翻译成英文.它似乎区分了异步性(是一个单词?)和线程,并暗示你可以拥有一个具有异步任务但没有多线程的程序.
现在我理解异步任务的想法,例如pg上的示例.Jon Skeet的C#In Depth,第三版中的 467
async void DisplayWebsiteLength ( object sender, EventArgs e )
{
label.Text = "Fetching ...";
using ( HttpClient client = new HttpClient() )
{
Task<string> task = client.GetStringAsync("http://csharpindepth.com");
string text = await task;
label.Text = text.Length.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
该async关键字的意思是" 这个功能,无论何时它被调用时,不会在这是需要的一切它的完成被称为它的呼叫后,上下文调用."
换句话说,将它写在某个任务的中间
int x = 5;
DisplayWebsiteLength();
double y = Math.Pow((double)x,2000.0);
Run Code Online (Sandbox Code Playgroud)
,因为DisplayWebsiteLength()与"无关" x或y将导致DisplayWebsiteLength()"在后台"执行,如
processor 1 | processor 2
-------------------------------------------------------------------
int …Run Code Online (Sandbox Code Playgroud) c# parallel-processing multithreading asynchronous async-await
我是TPL的新手,我想知道:C#5.0中新增的异步编程支持(通过new async和await关键字)如何与线程的创建有关?
具体来说,async/await每次使用它们时是否使用创建新线程?如果有许多嵌套方法使用async/await,是否为每个方法创建了一个新线程?
我有一个同时接收多个请求的网络服务。对于每个请求,我需要调用另一个网络服务(身份验证)。问题是,如果同时发生多个(>20)请求,响应时间会突然变得更糟。
我制作了一个示例来演示该问题:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace CallTest
{
public class Program
{
private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler { Proxy = null, UseProxy = false });
static void Main(string[] args)
{
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
// warmup
CallSomeWebsite().GetAwaiter().GetResult();
CallSomeWebsite().GetAwaiter().GetResult();
RunSequentiell().GetAwaiter().GetResult();
RunParallel().GetAwaiter().GetResult();
}
private static async Task RunParallel()
{
var tasks = new List<Task>();
for (var i = 0; i < 300; i++)
{
tasks.Add(CallSomeWebsite());
}
await …Run Code Online (Sandbox Code Playgroud) 我在这个网站上看到了一些关于Async和Await使用的帖子.很少有人说Async和Await在单独的后台线程上完成它的工作意味着产生一个新的后台线程,很少有人说没有意味着Async和Await没有启动任何单独的后台线程来完成它的工作.
所以任何人只要告诉我Async和Await在使用时会发生什么.
class Program
{
static void Main(string[] args)
{
TestAsyncAwaitMethods();
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
public async static void TestAsyncAwaitMethods()
{
await LongRunningMethod();
}
public static async Task<int> LongRunningMethod()
{
Console.WriteLine("Starting Long Running method...");
await Task.Delay(5000);
Console.WriteLine("End Long Running method...");
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Starting Long Running method...
Press any key to exit...
End Long Running method...
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
var things = await GetDataFromApi(cancellationToken);
var builder = new StringBuilder(JsonSerializer.Serialize(things));
await things
.GroupBy(x => x.Category)
.ToAsyncEnumerable()
.SelectManyAwaitWithCancellation(async (category, ct) =>
{
var thingsWithColors = await _colorsApiClient.GetColorsFor(category.Select(thing => thing.Name).ToList(), ct);
return category
.Select(thing => ChooseBestColor(thingsWithColors))
.ToAsyncEnumerable();
})
.ForEachAsync(thingAndColor =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId); // prints different IDs
builder.Replace(thingAndColor.Thing, $"{thingAndColor.Color} {thingAndColor.Thing}");
}, cancellationToken);
Run Code Online (Sandbox Code Playgroud)
它使用System.Linq.Async并且我发现很难理解。ToList()在“经典”/同步 LINQ 中,只有当我调用或ToArray()使用它时,整个事情才会执行。在上面的示例中,没有此类调用,但 lambda 无论如何都会执行。它是如何工作的?
我的另一个担忧是关于多线程。我多次听说异步!=多线程。那么,怎么可能打印Console.WriteLine(Thread.CurrentThread.ManagedThreadId);出各种ID呢?有些 ID 会被打印多次,但输出中总共有大约 5 个线程 ID。我的代码都没有显式创建任何线程。这都是异步等待。不StringBuilder支持多线程,我想了解上面的实现是否有效。
请忽略我代码的算法,这并不重要,这只是一个例子。重要的是 System.Async.Linq 的使用。