等待新的Task< T>(...):任务不运行? [英] Await new Task<T>( ... ) : Task does not run?
问题描述
A continuation of a question asked here :
在上述问题中,我具有以下函数,该函数返回Task类型的对象(用于增量测试):
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( );
} ) );
}
当我调用await GetInstance( );
时,将调用该函数(并且我假定由于未引发异常而返回了任务),但是任务只是坐在那里.
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.
我不希望此函数返回已 已在运行 (即 IMPERATIVE )的任务)
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?
推荐答案
要创建已开始的任务
尝试创建如下任务:
Task.Factory.StartNew<object>((Func<Task<object>>) ...);
要创建任务而不启动它
如果您不希望启动任务,只需按原样使用new Task<object>(...)
即可,但是在等待该任务之前,您需要在该任务上调用Start()
方法!
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!
我的推荐
只需创建一个返回匿名函数的方法,如下所示:
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( );
} );
}
然后获取它,并在需要时在新的Task
中运行它(还要注意,我已经从lambda表达式中删除了async/await
,因为您已经将它放入了Task中了):
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());
这样做的一个好处是,您也可以将其调用而无需将其放入Task
:
One advantage to this is that you can also call it without putting it into a Task
:
GetFunction()();
这篇关于等待新的Task< T>(...):任务不运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!