Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exactly result from async methods via await without Task.Result?

Tags:

c#

async-await

I wanted to experiment with async and await but I had a fiasco. I have the method which need to run two methods asynchronously(it works partly)

public void Run()
{
            Task[] tasks = new Task[2];
            tasks[0] = Task.Factory.StartNew(DisplayInt);
            tasks[1] = Task.Factory.StartNew(DisplayString);

            //block thread until tasks end
            Task.WaitAll(tasks);
}

And two methods which are used

public async void DisplayInt()
    {
        Task<int> task = new Task<int>(
            () => 10);
        task.Start();
        Console.WriteLine(await task);
    }

    public async void DisplayString()
    {
        Task<string> task = new Task<string>(
           () => "ok" );
        task.Start();
        Console.WriteLine(await task);
   }

And usually I got next results:1) 10 ok

or 2)ok 10

but sometimes I got 3)nothing

How to get exactly result from async methods via await without using task.Result or it cannot happen?

like image 859
Bushuev Avatar asked Mar 15 '23 10:03

Bushuev


1 Answers

I recommend you read some introductory articles like my own async intro, and follow that up with my MSDN article on async best practices. If you just bang out code, you're going to end up with a lot of pain.

In particular, you should not use Task.Factory.StartNew, the Task constructor, nor Task.Start; and you should avoid async void (all links are to my blog where I explain in detail why).

To answer your actual question:

How to get exactly result from async methods via await without using task.Result or it cannot happen?

To get the result from a task, you can either asynchronously wait for the task to complete (via await), or you can synchronously (blocking) wait for the task to complete (via Result). There's no "other way", if that's what you're asking.

like image 94
Stephen Cleary Avatar answered Apr 26 '23 12:04

Stephen Cleary