如何在不启动任务的情况下构造任务?

问题描述:

我想使用

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");