egon12
egon12

Reputation: 43

How to properly use async await

I tried out a few things with async/await but I dont't realy get it. 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

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()?

Upvotes: 2

Views: 754

Answers (2)

i3arnon
i3arnon

Reputation: 116518

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:

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.

Upvotes: 8

usr
usr

Reputation: 171178

You could use an async Task method and call Wait on the resulting task. 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. All your code runs single threaded, yet you can have multiple async methods executing.

Upvotes: 0

Related Questions