更新时间:2021-12-02 21:30:20
要创建已开始的任务
尝试创建如下任务:
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()();