C#中的多线程超时处理实践方案

2019-12-30 19:12:15刘景俊

假设我们调用StartWithTimeout 10秒超时。1秒后,我们再次调用另一个StartWithTimeout,超时时间为10秒。再过1秒后,我们再次调用另一个StartWithTimeout,超时时间为10秒。然后我们调用StopOperationIfNotStartedYet()。

目前有3个操作超时,等待启动。 预期的行为是其中一个被停止, 其他2个操作应该能够正常启动。

我们的Program.cs可以像以前一样保持不变。 OperationHandler做了一些调整:


public class OperationHandler
{
 private IOperation _operation;
 private AutoResetEvent _are = new AutoResetEvent(false);

 public OperationHandler(IOperation operation)
 {
 _operation = operation;
 }
 public void StartWithTimeout(int timeoutMillis)
 {
 _are.Reset();
 Task.Factory.StartNew(() =>
 {
  bool wasStopped = _are.WaitOne(timeoutMillis);
  if (!wasStopped)
  _operation.DoOperation();
 });
 } 
 public void StopOperationIfNotStartedYet()
 {
 _are.Set();
 }
}

执行结果是:


Starting with timeout of 10 seconds, 3 times
Operation started
Operation started
Operation started
Starting with timeout of 10 seconds 3 times, but cancelling after 5 seconds
Operation started
Operation started
Finished...

结语

在处理线程通信时,超时后继续执行某些操作是常见的应用。我们尝试了一些很好的解决方案。一些解决方案可能看起来不错,甚至可以在特定的流程下工作,但是也有可能在代码中隐藏着致命的bug。当这种情况发生时,我们应对时需要特别小心。

AutoResetEvent和ManualResetEvent是非常强大的类,我在处理线程通信时一直使用它们。这两个类非常实用。正在跟线程通信打交道的朋友们,快把它们加入到项目里面吧!

总结

以上所述是小编给大家介绍的C#中的多线程超时处理实践方案,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!


注:相关教程知识阅读请移步到c#教程频道。