我必须在一个线程中执行一个长的进程操作,并继续将结果返回给一个函数.这是我的代码:
Task<ProductEventArgs>.Factory.StartNew(() =>
{
try
{
// long operation which return new ProductEventArgs with a list of product
}
catch (Exception e)
{
return new ProductEventArgs() { E = e };
}
}).ContinueWith((x) => handleResult(x.Result), TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)
问题实际上我没有超时.我想放一个计时器,以便返回这样的东西:
new ProductEventArgs() { E = new Exception("timeout") };
Run Code Online (Sandbox Code Playgroud)
如果达到超时.不能使用await/async.非常感谢 !
我试图使用下面的函数不返回true/false,除非布尔函数arg返回true或超时到期.在当前状态下,如果布尔函数arg返回false,则立即返回false而不是循环并重试X更多毫秒.
public delegate bool BooleanFunction ();
public static async Task<bool> Wait(uint Milliseconds, BooleanFunction Function)
{
var StartTime = Environment.TickCount;
do
{
if (Function())
{
return true;
}
Thread.Yield();
}
while (Environment.TickCount < StartTime + Milliseconds);
return false;
}
Run Code Online (Sandbox Code Playgroud)