-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
  • 39
  • 4
  • 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

1 Answers1

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
  • 490
  • 5
  • 8