C#任务工厂超时 [英] C# task factory timeout
问题描述
我在一个线程中执行一个漫长的过程操作和结果返回到功能继续。这里是我的code:
I have to execute a long process operation in a thread and continue by returning the result to a function. Here is my code :
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());
问题其实我没有超时。我想提出一个定时器,以便返回这样的事情:
The problem is actually I don't have a timeout. I want to put a timer in order to return something like this :
new ProductEventArgs() { E = new Exception("timeout") };
如果达到超时。
不能使用的await /异步。
非常感谢!
if the timeout is reached. Can't use await/async. Thanks a lot !
推荐答案
这code做了你有什么恩$ P $这里pssed:
This code does what you have expressed here:
var timeout = TimeSpan.FromSeconds(5);
var actualTask = new Task<ProductEventArgs>(() =>
{
var longRunningTask = new Task<ProductEventArgs>(() =>
{
try
{
Thread.Sleep(TimeSpan.FromSeconds(10)); // simulates the long running computation
return new ProductEventArgs();
}
catch (Exception e)
{
return new ProductEventArgs() { E = e };
}
}, TaskCreationOptions.LongRunning);
longRunningTask.Start();
if (longRunningTask.Wait(timeout)) return longRunningTask.Result;
return new ProductEventArgs() { E = new Exception("timed out") };
});
actualTask.Start();
actualTask.Wait();
Console.WriteLine("{0}", actualTask.Result.E); // handling E
正如你所看到 longRunningTask
与 TaskCreationOptions.LongRunning
选项创建的。这样,就会有专门的发
为它的执行,通过占领一个线程不与线程池
的正常行为干扰从那里太久 - 这将需要像IE用户界面的其他事情。 这很重要,长时间运行的任务
As you see longRunningTask
is created with TaskCreationOptions.LongRunning
option. That way it will have a dedicated Thread
for it's execution and does not interfere with normal behavior of ThreadPool
by occupying a thread from there for too long - which will be needed for other thing like i.e. UI. That's important for long running tasks.
请注意:然后,您可以处理 actualTask
与 ContinueWith
,但我想前preSS的精髓在这里
Note: You could then handle actualTask
with ContinueWith
but I wanted to express the essence here.
这篇关于C#任务工厂超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!