Await new Task( … ) : Task does not run?

前端 未结 4 2030
暖寄归人
暖寄归人 2021-01-02 02:20

A continuation of a question asked here :

In the aforementioned question I have the following function which returns an object of type Task (for incremental testing

4条回答
  •  臣服心动
    2021-01-02 02:51

    You should never use the Task constructor (or Task.Start).

    I do not want this function to return a task that is already running ( that is IMPERATIVE ).

    So, you want to return some code that won't execute until you call it? That's a delegate, not a Task.

    private static Func> GetInstance()
    {
      return async () =>
      {
        await SimpleMessage.ShowAsync("TEST");
        return new object();
      };
    }
    

    When you're ready to execute it, call it just like any other delegate. Note that it returns a Task, so you can await the result:

    var func = GetInstance();
    // Delegate has not started executing yet
    var task = func();
    // Delegate has started executing
    var result = await task;
    // Delegate is done
    

提交回复
热议问题