-1

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.

awp-sirius
  • 59
  • 6
  • 2
    That's not clear. What exactly do you need? – McNets May 16 '22 at 09:34
  • https://stackoverflow.com/questions/52936526/reference-async-task-without-starting-it – RelativeLayouter May 16 '22 at 09:37
  • Depending on your use case, a `Func>` might be helpful. There is no easy syntax to create cold tasks, so without this you're looking at something like Reactive Extensions (`Observable.Defer`), which has a bit of a learning curve. You could also start your task by waiting on something, like an event, so you can "start" it explicitly yourself. – Jeroen Mostert May 16 '22 at 09:38
  • It is interesting. So "out of the box", I can only create non-asynchronous tasks. Task tsk = new Task(Test); – awp-sirius May 16 '22 at 09:44
  • Related: [How to construct a Task without starting it?](https://stackoverflow.com/questions/16066349/how-to-construct-a-task-without-starting-it) – Theodor Zoulias May 16 '22 at 12:18

2 Answers2

2

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>.

Clemens
  • 588
  • 6
  • 9
0

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.
Ed Ames
  • 1
  • 2