繁体   English   中英

Task.Factory.StartNew <TResult> (功能 <Object, TResult> ,对象状态)生成错误

[英]Task.Factory.StartNew<TResult> (Func<Object, TResult>, object state) build error

当我编译代码时遇到此错误,我无法弄清楚为什么mcs查找错误的函数重载,我使用git作为git当前活动开发版本的最新版本,我检查了TaskFactory类源代码和函数存在!


TaskPoc.cs(30,20):错误CS1502:最佳重载方法匹配` System.Threading.Tasks.TaskFactory.StartNew<bool>(System.Func<bool>, System.Threading.Tasks.TaskCreationOptions) '有一些无效参数/usr/local/lib/mono/4.5/mscorlib.dll(与先前错误相关的符号的位置)TaskPoc.cs(30,56):错误CS1503:参数`#1'无法转换` System.Func<TaskPoc.State,bool> '表达式以键入` System.Func<bool> '


using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskPoc
{
  public class State
  {
    public int num;
    public string str;
  }

  public class App
  {
    public static void Main(string[] args)
    {
      State state = new State();
      state.num = 5;
      state.str = "Helllllllllllo";

      TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(state);
      Task<bool> taskObj = taskCompletionSource.Task;

      Func<State, bool> userMethod = (stateObj) =>
        {
            bool result = TestMethod(stateObj.num, stateObj.str);
            taskCompletionSource.SetResult(result);
            return result;
        };

      Task.Factory.StartNew<bool>(userMethod, state);

      bool result2 = taskObj.Result;
      Console.WriteLine("Result: ", result2.ToString());
    }

    public static bool TestMethod(int num, string str)
    {
      Thread.Sleep(1000);
      Console.WriteLine(string.Format("{0} {1}", num, str));
      return true;
    }
  }
}

我假设您想要此重载: TaskFactory.StartNew <TResult>(Func <Object,TResult>,Object)

如您所见, Func<Object, TResult>必须是Object ,而不是State

您可以按以下方式修复代码:

Func<object, bool> userMethod = (state) =>
{
    State stateObj = (State)state;
    bool result = TestMethod(stateObj.num, stateObj.str);
    taskCompletionSource.SetResult(result);
    return result;
};

请注意,您的代码可以缩短,如下所示:

public static void Main(string[] args)
{
    int num = 5;
    string str = "Helllllllllllo";

    Task<bool> taskObj = Task.Run<bool>(() => TestMethod(num, str));

    bool result2 = taskObj.Result;
    Console.WriteLine("Result: {0}", result2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM