如何在不启动任务的情况下构造任务? [英] How to construct a Task without starting it?
本文介绍了如何在不启动任务的情况下构造任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I want to use this Task<TResult>
constructor. I can't seem to get the syntax right. Could someone correct my code?
此外,我是否正确地认为,如果以这种方式构造Task
,它就不会启动?
Also, am I right thinking that if a Task
is constructed that way, it's not started?
我认为我需要的构造函数是:
The constructor I think I need is:
Task<TResult>(Func<Object, TResult>, Object)
我得到的错误是:
参数1:无法从方法组"转换为"
System.Func<object,int>
"
static void Main(string[] args)
{
var t = new Task<int>(GetIntAsync, "3"); // error is on this line
// ...
}
static async Task<int> GetIntAsync(string callerThreadId)
{
// ...
return someInt;
}
推荐答案
var t = new Task<int>(() => GetIntAsync("3").Result);
或
var t = new Task<int>((ob) => GetIntAsync((string) ob).Result, "3");
为避免使用lambda,您需要编写这样的静态方法:
To avoid using lambda, you need to write a static method like this:
private static int GetInt(object state)
{
return GetIntAsync(((string) state)).Result;
}
然后:
var t = new Task<int>(GetInt, "3");
这篇关于如何在不启动任务的情况下构造任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文