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.
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.
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>
.
You can create a cold Task by wrapping it in another Task. The outer task creates the inner one without starting it.
//. If you don't call Start() and then await
//. Your code will never fire
public static async RunMe() {
var coldTask = new Task<Task<string>>(GetString);
// To start the task
coldTask.Start();
// And then let it finish
await coldTask;
}
// sharplab.io shows how C# compiles the async keyword
//. into a state machine that creates the inner task without starting it.