有工作要做时挂起并通知线程 [英] Suspending and notifying threads when there is work to do

查看:94
本文介绍了有工作要做时挂起并通知线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个线程(正在IIS上运行的C#应用​​程序)正在运行,所有线程都需要与同一个MQ后端进行通信.为了最大程度地减少网络流量,我仅在有工作要做时才发送后端请求.将有一个线程监视是否有工作要做,它需要通知其他线程它们也应该开始处理.当前的解决方案包括监视线程设置全局变量并使其他线程循环并检查,即在监视线程中进行检查:

I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threads that they should also begin processing. The current solution involves the monitor thread setting a global variable and having the other threads loop and check that, ie in the monitor thread:

CheckIfWorkAvailable() {
  while(true) {
    if (queue.Empty != true) {
      workToBeDone = true;
    }
  }//end while loop
}

,然后在工作线程中:

DoWork() {
  while(true) {
    if (workToBeDone == true) {
      //do work...
    }
    else {
      Thread.Sleep(x seconds)
    }
  }//end while loop
}

在有工作要做时,监视器线程是否可以通知工作线程,而不是让它们只是循环并进入睡眠状态?辅助线程还设置了一个计数器,指示它们正在工作,并在完成工作时递减该计数器,因此可以将workToBeDone标志设置为false.

Can the monitor thread notify the worker threads when there is work to do instead of having them just loop and sleep? The worker threads also set a counter indicating they are working and the decrement it when their work is done so the workToBeDone flag can be set to false.

推荐答案

签出 WaitHandle 及其降级类. EventWaitHandle 可能适合您的需求.

Check out WaitHandle and its descending classes. EventWaitHandle may suit your needs.

这篇关于有工作要做时挂起并通知线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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