Home > other >  Create async Task<T> without run
Create async Task<T> without run

Time:05-16

How can I create a async Task but not run it right away?

private static async Task<string> GetString()
{
    await Task.Delay(5000);
    return "Finish";
}

Task<string> str = GetString();

This immediately starts the task.

CodePudding user response:

If you want dereferred excecution use Func.

private static Func<Task<string>> GetStringFunc()
    => GetString;

Thus:

var deferred = GetStringFunc();
/*whatever*/
var task = deferred();

Update: please have a look at Lazy<T>.

  • Related