[英]Synchronously run a task in the same thread (no threadpool) with a timeout
I want to use Task<> type, but not with TPL, but with .NET4.5/C#async instead. 我想使用Task <>类型,但不是使用TPL,而是使用.NET4.5 / C#async。
Thing is, I have some requirements for my case: 事实是,我对我的案子有一些要求:
RunSynchronously()
, others Wait()
, and others ContinueWith(_, TaskContinuationOptions.ExecuteSynchronously)
, which one is the adequate here?). RunSynchronously()
,其他人Wait()
,还有其他的ContinueWith(_, TaskContinuationOptions.ExecuteSynchronously)
,哪一个就足够了?)。 For the latter, I think I need Task.Delay()
but I'm not sure how to combine it with the first two requirements. 对于后者,我认为我需要
Task.Delay()
但我不确定如何将它与前两个要求结合起来。 Thanks 谢谢
This answer is based on @svick's comment. 这个答案是基于@ svick的评论。
I'm going to make the assumption that you want all the "work" of the method to be done on the same thread as the caller, but that you don't mind if a thread pool thread is used for cancellation purposes (I'm assuming this since you mentioned Task.Delay
which will use a Timer
which will use a thread pool thread when the timer fires. 我将假设您希望方法的所有“工作”都在与调用者相同的线程上完成,但是您不介意线程池线程是否用于取消目的(I'假设这是因为你提到了
Task.Delay
,它将使用一个Timer
,当计时器触发时它将使用一个线程池线程。
That said, there would be no need for Task
, since when the method returns you would know for certain that the Task was completed. 也就是说,不需要
Task
,因为当方法返回时,您肯定知道任务已完成。 Just a regular method with a timeout will do: 只是一个超时的常规方法会:
static void DoSomethingOrThrowAfterTimeout(int millisecondsTimeout)
{
CancellationTokenSource cts = new CancellationTokenSource(millisecondsTimeout);
CancellationToken ct = cts.Token;
// do some work
ct.ThrowIfCancellationRequested();
// do more work
ct.ThrowIfCancellationRequested();
// repeat until done.
}
Obviously, with this approach of using cooperative cancellation, the method won't timeout exactly at the timeout, as it will be dependent on how small you can split up the work in the method. 显然,使用这种使用协作取消的方法,该方法不会在超时时准确超时,因为它取决于您在方法中拆分工作的程度。
If you want to avoid the usage of another thread (for the CancellationTokenSource
), then you could track the starting time and then check how much time has passed (to see if you've exceeded the timeout) at various points in the method (like how ct.ThrowIfCancellationRequested()
is used above. 如果你想避免使用另一个线程(对于
CancellationTokenSource
),那么你可以跟踪开始时间,然后在方法的不同点检查已经过了多少时间(看你是否超过了超时)(比如如何在上面使用ct.ThrowIfCancellationRequested()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.