当我编译代码时我得到了这个错误,我无法弄清楚为什么mcs会查找错误的函数重载,我使用mono作为当前最新的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;
}
}
}
答案 0 :(得分:3)
我假设你想要这个重载: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);
}