【问题标题】:c# - Threadpool notifies when complete, not blocking main threadc# - 线程池在完成时通知,不阻塞主线程
【发布时间】:2013-11-27 06:16:39
【问题描述】:

所以我想知道当线程池执行完成时调用函数的最佳方法是什么?

我必须通过线程池处理数据集。集合 A 必须在集合 B 之前完成。我遇到的问题是我不能让主线程等到集合 A 完成后再处理集合 B。所以我需要在线程计数之后触发事件或调用函数池已减少到零(我正在使用互锁对象来维护线程数),我只是想知道这样做的最佳方法是什么?

感谢您的帮助,希望我的问题没有含糊。

【问题讨论】:

标签: c# multithreading threadpool


【解决方案1】:

为了解决这个问题,我建议您使用 TaskContinueWith() 方法。内部任务使用 ThreadPool 类,但它们更加灵活。例如:

Task.Run(() => Console.WriteLine("Main task"))
            .ContinueWith(task => Console.WriteLine("Continue task"), TaskContinuationOptions.NotOnFaulted);

【讨论】:

    【解决方案2】:

    您可以使用基于等待和信号标准的 CountdownEvent 点击 [这里] (http://msdn.microsoft.com/en-us/library/system.threading.countdownevent(v=vs.110).aspx) 了解更多信息

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      相关资源
      最近更新 更多