Task.Run 不明确的参数重载

Task.Run Ambiguous Parameter Overloads

我在 C# 中使用任务 class 并想传递一个预定义的方法 returns 一个值而不使用 lambdas 到 Task.Run 方法。

这是一个带有代码的控制台应用程序:

static int ThreadMethod()
{
    return 42;
}

static void Main(string[] args)
{
    Task<int> t = Task.Run(function:ThreadMethod);
    WriteLine(t.Result);
}

但是,它返回了这个错误:

The call is ambiguous between the following methods or properties: 'Task.Run<TResult>(Func<TResult>)' and 'Task.Run(Func<Task>)'

我尝试这样做来修复它并得到了我预期的结果:

Task<int> t = Task.Run((Func<int>)ThreadMethod);

但是,我不确定我这样做是否正确,或者是否有更好的解决方案?

修正您的 .运行 参数,如本例所示。可以复制粘贴到LinqPad进行测试。

public static void Main(string[] args)
{
    Task<int> t = Task.Run(() => ThreadMethod());
    WriteLine(t.Result);
}

public static int ThreadMethod()
{
    return 42;
}

如果您想将其视为一个变量以通过以下检查:

public static void Main(string[] args)
{

    //Func<int> is saying I want a function with no parameters
    //but returns an int. '() =>' this represents a function with 
    //no parameters. It then points to your defined method ThreadMethod
    //Which fits the notions of no parameters and returning an int.

    Func<int> threadMethod = () => ThreadMethod();

    Task<int> t = Task.Run(threadMethod);
    Console.WriteLine(t.Result);
}

public static int ThreadMethod()
{
    return 42;
}

这是 Func(T) 上的Documentation,在左侧菜单中,您可以select Func() 对象的不同变体。