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

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

    You are stuck with a bad design there. I'll try to make something work for you under these constraints.

    The only way to delay start tasks is to use the Task.Start method. (You also can use RunSynchronously but that doesn't really make use of any of the tasks features. At this point the task becomes an unthreaded lazy object.

    So use the Task.Start method.

    await does not start tasks. It waits for tasks that already run. Therefore await new Task(() => { }) always freezes forever.

    Another problem here:

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

    When you start that task it will complete nearly instantly and Task.Result will hold another task - the one returned by the async lambda. I doubt this is what you want. Hard to make this work and I don't know what you need.

    This smells like the XY problem. Can you elaborate on what you want to accomplish? It feels like you have given yourself unnecessary constraints.

    提交回复
    热议问题