[英]How to use Task.Factory.StartNew<TResult> when TResult is a Task<object>
[英]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.