[英]Task.Factory.StartNew<TResult> (Func<Object, TResult>, object state) build error
when I compile the code I get this error, I couldn't figure out why mcs looks for the wrong function overload, I'm using mono as latest of current active development version from git, I checked the TaskFactory class source code and the function exists ! 当我编译代码时遇到此错误,我无法弄清楚为什么mcs查找错误的函数重载,我使用git作为git当前活动开发版本的最新版本,我检查了TaskFactory类源代码和函数存在!
TaskPoc.cs(30,20): error CS1502: The best overloaded method match for `
System.Threading.Tasks.TaskFactory.StartNew<bool>(System.Func<bool>, System.Threading.Tasks.TaskCreationOptions)
' has some invalid arguments /usr/local/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error) TaskPoc.cs(30,56): error CS1503: Argument `#1' cannot convert `System.Func<TaskPoc.State,bool>
' expression to type `System.Func<bool>
' 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;
}
}
}
I assume you want this overload: TaskFactory.StartNew<TResult>(Func<Object, TResult>, Object) 我假设您想要此重载: TaskFactory.StartNew <TResult>(Func <Object,TResult>,Object)
As you can see, the argument of the Func<Object, TResult>
must be Object
, not State
. 如您所见, Func<Object, TResult>
必须是Object
,而不是State
。
You can fix your code as follows: 您可以按以下方式修复代码:
Func<object, bool> userMethod = (state) =>
{
State stateObj = (State)state;
bool result = TestMethod(stateObj.num, stateObj.str);
taskCompletionSource.SetResult(result);
return result;
};
Note that your code can be shortened as follows: 请注意,您的代码可以缩短,如下所示:
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.