从我的理解主要事情之一async和await要做的就是让代码易于读写-但使用它们等于产卵后台线程来执行持续时间长的逻辑?
我正在尝试最基本的例子.我在内联添加了一些评论.你能为我澄清一下吗?
// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
Task<int> access = DoSomethingAsync();
// task independent stuff here
// this line is reached after the 5 seconds sleep from
// DoSomethingAsync() method. Shouldn't it be reached immediately?
int a = 1;
// from my understanding the waiting should be done here.
int x = await access;
}
async Task<int> DoSomethingAsync()
{
// is …Run Code Online (Sandbox Code Playgroud) 我认为它们基本上是相同的 - 编写在处理器之间分割任务的程序(在具有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
我正在通过 Andrew Troelsen 的书“Pro C# 7 With .NET and .NET Core”学习 C#。在第 19 章(异步编程)中,作者使用了这些示例代码:
static async Task Main(string[] args)
{
Console.WriteLine(" Fun With Async ===>");
string message = await DoWorkAsync();
Console.WriteLine(message);
Console.WriteLine("Completed");
Console.ReadLine();
}
static async Task<string> DoWorkAsync()
{
return await Task.Run(() =>
{
Thread.Sleep(5_000);
return "Done with work!";
});
}
Run Code Online (Sandbox Code Playgroud)
作者接着说
"... this 关键字 (await) 将始终修改返回 Task 对象的方法。当逻辑流到达 await 标记时,调用线程将在此方法中挂起,直到调用完成。如果您要运行此版本在应用程序中,您会发现 Completed 消息显示在 Done with work! 消息之前。如果这是一个图形应用程序,用户可以在 DoWorkAsync() 方法执行时继续使用 UI”。
但是当我在 VS 中运行这段代码时,我没有得到这种行为。主线程实际上被阻塞了 5 秒,直到“完成工作!”之后才会显示“完成”。
查看有关 async/await 如何工作的各种在线文档和文章,我认为“await”会起作用,例如当遇到第一个“await”时,程序会检查该方法是否已经完成,如果没有,它会立即“ …