螺纹延误倒计时通知最佳实践 [英] Best Practice for thread delays with countdown notification

查看:160
本文介绍了螺纹延误倒计时通知最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于使用下面的模式有很多不同的地方进行定时延迟倒计时通知事件,并取消的能力:

I tend to use the following pattern a lot of different places for a timed delay with countdown notification events, and the ability to cancel:

CancellationToken ctoken = new CancellationToken();
for (int i = 0; i < 10; i++)
{
    if (ctoken.IsCancellationRequested) break;
    Thread.Sleep(1000);
    if (ctoken.IsCancellationRequested) break;
    if (Status != null) Status(this, new StatusEventArgs(i));
}

我想这样做是抽象的,这种模式到自己的系统,我可以用它来阻止任何特定线程,直到倒计时为止。是否有某种为这个最佳实践?它必须提供细粒度的状态反馈(preferably我可以告诉它通知我的每一秒,十分之一秒,等),它必须(pferably $ P $比每秒好转反应)支持取消。我觉得我应该使用新的 CountdownEvent 的功能在.NET 4.0中,或者使用显示器,而不是仅仅睡,但我希望在这里一些更好的洞察力。

What I would like to do is abstract this pattern into its own system I can use to block any particular thread until a countdown is reached. Is there some sort of best practice for this? It must provide granular status feedback (preferably I could tell it to notify me every second, tenth of a second, etc.), and it must support cancellation (preferably with better response than each second). I feel I should be using the new CountdownEvent feature in .NET 4.0, or maybe use a Monitor instead of just sleeping, but I'm hoping for some better insight here.

推荐答案

你应该做的第一件事是分开的反馈和取消的想法。也就是说,你有一个反馈机制和解除机构,但它们不是在所有相关。如果你能区分这两个概念,那么事情就比较容易处理,也将有更好的表现。

The first thing you should do is separate the ideas of feedback and cancellation. That is, you have a feedback mechanism and a cancellation mechanism, but they are not at all related. If you can separate those two concepts, then things get easier to deal with and also will perform better.

您想提供反馈,在一定的时间间隔,这意味着一个计时器。并且,而不是投票,看看是否取消请求,你可以等待在等待句柄。

You want to provide feedback at some interval, which implies a timer. And rather than polling to see if cancellation is requested, you can wait on the wait handle.

是这样的:

int i = 0;
using (System.Threading.Timer tmr = new System.Threading.Timer((s) =>
    {
        if (Status != null) Status(this, new StatusEventArgs(i));
        ++i;
    }, null, 1000, 1000))
{
    token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10)));
}

我假设你得到的CancellationToken 从别的地方(即它的传递,或者将其定义及其他可能影响其状态)。

I assume that you're getting the CancellationToken from somewhere else (i.e. it's passed in, or you define it and others can affect its state).

这篇关于螺纹延误倒计时通知最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆