Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - Await new Task<T>( ... ) : Task does not run?

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 purposes) :

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

When I call await GetInstance( );, the function is called (and I assume the task is returned since no exception is thrown) but then the task just sits there.

I can only guess I am doing this wrong then.

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

How do I asynchronously run the task returned by this function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To create a Task already started

Try creating the task like this:

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

To create a Task without starting it

If you don't want the task started, just use new Task<object>(...) 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<object> GetFunction( ) {
    return (Func<object>)(( ) => {
        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<object>(GetFunction());

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

GetFunction()();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...