How to receive result from asynchronous methods through waiting without Task.Result?

I wanted to experiment with asynx and wait, but I had a fiasco. I have a method that should run two methods asynchronously (it works partially)

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 that 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 the following results: 1) 10 ok

or 2) good 10

but sometimes I have 3) nothing

How to get the exact result from async methods through await without using task.Result or it can't happen?

+4
source share
2 answers

, async intro, MSDN . , .

, Task.Factory.StartNew, Task, Task.Start; async void ( , ).

:

async await task.Result ?

, ( await), () ( Result). " ", , .

+6

SO...

, , . ( ). DisplayString :

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

DisplayString 10 , :

10    
ok

P.S. , async / await. WinForms, Console.

+1

Source: https://habr.com/ru/post/1612073/


All Articles