简体   繁体   English

如何正确使用异步等待

[英]How to properly use async await

I tried out a few things with async/await but I dont't realy get it. 我尝试了async / await的一些东西,但我真的没有得到它。 All I want to achive for the beginning is to concurrently write to the Console from two different Threads. 我想要开始的所有内容是同时从两个不同的线程写入控制台。 Here is the code: 这是代码:

static void Main(string[] args)
{
    DoSomethingAsync();

    for (int i = 0; i < 1000; i++)
        Console.Write(".");

    Console.ReadLine();
}

static async void DoSomethingAsync()
{
    Console.WriteLine("DoSomethingAsync enter");

    //This does not seem good
    await Task.Delay(1);

    for (int i = 0; i < 1000; i++)
        Console.Write("X");

    Console.WriteLine("DoSomethingAsync exit");
}

With Threads that was easy but with async/await I only get it done when I put in this strange 使用Threads很容易但是使用async / await我只能在完成这个奇怪的操作时完成它

await Task.Delay(1);

Most basic examples I saw used this. 我看到的大多数基本例子都使用过它 But what to do, when you want to do something timetaking that is not async? 但是,当你想做一些不同步的时间时,该怎么做? You cant await anything and so all code runs on the main Thread. 你不能等待任何东西,因此所有代码都在主线程上运行。 How can I achive the same behavior as with this code but without using Task.Delay()? 如何在不使用Task.Delay()的情况下实现与此代码相同的行为?

Parallel and concurrent are not the same thing. 并行和并发不是一回事。 If you want your for loop to be executed in parallel use Task.Run to offload that work to a different ThreadPool thread: 如果您希望并行执行for循环,请使用Task.Run将该工作卸载到另一个ThreadPool线程:

static void Main(string[] args)
{
    var task = Task.Run(() => DoSomething());

    for (int i = 0; i < 1000; i++)
        Console.Write(".");

    task.Wait() 
}

static void DoSomething()
{
    for (int i = 0; i < 1000; i++)
        Console.Write("X");
}

async-await is used for asynchronous operations, which may run concurrently but not necessarily . async-await用于异步操作, 可以同时运行但不一定

You could use an async Task method and call Wait on the resulting task. 您可以使用async Task方法并在生成的任务上调用Wait This will work. 这会奏效。 It will, however, introduce concurrency because timer ticks are served on the thread pool. 但是,它会引入并发性,因为在线程池上提供了计时器滴答。 I'm not sure what thread-safety guarantees the console makes. 我不确定控制台的线程安全性是什么。

Consider setting up a single threaded synchronization context. 考虑设置单线程同步上下文。 Such a thing behaves very much like a UI thread. 这样的事情非常像UI线程。 All your code runs single threaded, yet you can have multiple async methods executing. 您的所有代码都运行单线程,但您可以执行多个异步方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM