Method that returns Task <string>

I need a method that returns Task<string>with an empty string like

public static Task<string> AsyncTest()
{    
     return new Task<string>(() => string.Empty); //problem here

     // this method would work:
     // return new WebClient().DownloadStringTaskAsync(@"http://www.google.de");   
}

public static void Workdl(string input)
{
    Console.Write("OUT: " + input.Substring(0, 100));
}

This snippet compiles, but when I call it

Task<string> dlTask = AsyncTest();
Workdl(await dlTask);
await Task.WhenAll(dlTask); //Task never completes 

he never determines.

+4
source share
2 answers

If you are not writing your own task management system, you should probably never use it new Task(...).

However, aside, the reason why this does not work in this case is because it new Task(...)does not start by itself. It just creates a task object around your delegate.

You must either explicitly run it:

var t = new Task(() => string.Empty);
t.Start();
return t;

Or just use Task.Runinstead:

return Task.Run(() => string.Empty);

( new Task(...))

, - .

, . , "", , , , . , , , , :

return Task.FromResult(string.Empty);

" ".

+15

Task.FromResult()

return Task.FromResult(string.Empty);
+6

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


All Articles