[英]why I should use await?
I am new to async / await. 我是异步/等待新手。 but I created the POC but I am still confused.
但是我创建了POC,但我仍然感到困惑。
Outcome of method 方法结果
public async void WriteLineFunc(string str)
{
await Task.Factory.StartNew(() => WaitFor2Secs());
//WaitFor2Secs();
Console.WriteLine(str);
}
and 和
public async void WriteLineFunc(string str)
{
//await Task.Factory.StartNew(() => WaitFor2Secs());
WaitFor2Secs();
Console.WriteLine(str);
}
is same. 是同样的。 What is point of making a method as await?
使方法处于等待状态有什么意义? Just to run a function on other thread and wait for its completion?
只是要在其他线程上运行一个函数并等待其完成?
When a method uses await
, it can return to its caller before it's complete. 当方法使用
await
,它可以在完成之前返回其调用方。
Consider this example: 考虑以下示例:
public async Task WriteLineFuncAsync(string str)
{
await Task.Delay(2000);
Console.WriteLine(str);
}
public void WriteLineFunc(string str)
{
Thread.Sleep(2000);
Console.WriteLine(str);
}
WriteLineFunc
will synchronously block the running thread for 2 seconds and then write out the string. WriteLineFunc
将同步阻塞正在运行的线程2秒钟,然后写出该字符串。 WriteLineFuncAsync
will immediately return an incomplete Task
to its caller; WriteLineFuncAsync
将立即将不完整的Task
返回给其调用者; two seconds later, it will write out the string and then complete the Task
. 两秒钟后,它将写出字符串,然后完成
Task
。
For client-side applications, the main benefit is responsiveness (the GUI thread is not blocked). 对于客户端应用程序,主要优点是响应能力 (GUI线程未阻塞)。 For server-side applications, the main benefit is scalability (you can have far more responses than threads).
对于服务器端应用程序,主要好处是可伸缩性 (与线程相比,您可以得到更多的响应)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.