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

前端 未结 4 2017
暖寄归人
暖寄归人 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:37

    To create a Task already started

    Try creating the task like this:

    Task.Factory.StartNew((Func>) ...);
    
    
    

    To create a Task without starting it

    If you don't want the task started, just use new Task(...) as you were using, but then you need to call Start() method on that task before awaiting it!

    [Reference]

    My recommendation

    Just make a method that returns the anonymous function, like this:

    private static Func GetFunction( ) {
        return (Func)(( ) => {
            SimpleMessage.Show( "TEST" );
            return new object( );
        } );
    }
    
    
    

    Then get it and run it in a new Task whenever you need it (Also notice that I removed the async/await from the lambda expression, since you are putting it into a Task already):

    Task.Factory.StartNew(GetFunction());
    
    
    

    One advantage to this is that you can also call it without putting it into a Task:

    GetFunction()();
    

    提交回复
    热议问题