.NET - 线程同步

时间:2010-01-14 01:10:29

标签: c# synchronization multithreading

我一直在研究一个只要应用程序正在运行就会生存的线程,并以500毫秒的间隔运行。我注意到,如果队列中没有任何内容可供处理,我可能会无用处理,所以我到处查看本地的一些来源,我发现了一个接近我的例子,但它是用Java编写的。

这个例子有这个:

synchronized(this) {
    try {
        wait();
    } catch (InterruptedException e) {
        cleanup();
        break;
    }
}

在一个永远持续的while循环中。

线程有此通知等待:

synchronized(this) {
    notifyAll();
}

这是在enqueue线程中。 我还要你注意,该类继承了Runnable。

有人能快速解释C#中的相应功能吗?如果可以,也许就是一个例子!

4 个答案:

答案 0 :(得分:5)

.NET / C#最佳做法是使用EventWaitHandle

你可以在线程之间共享一些变量:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset);

在消费者线程(你现在每500毫秒唤醒一个)中,你将循环等待句柄(可能是超时):

try
{
    while(true)
    {
        handle.WaitOne();
        doSomething();
    }
}
catch(ThreadAbortException)
{
    cleanup();
}

在生产者线程中:

produceSomething();
handle.Set();

答案 1 :(得分:1)

也许您可以使用阻止队列:http://www.eggheadcafe.com/articles/20060414.asp

除了Dequeue函数之外,它是一个队列,直到有一个对象返回。

用法:

BlockingQueue q = new BlockingQueue();

  void ProducerThread()
  {
    while (!done)
      {
        MyData d = GetData();
        q.Enqueue(d);
        Thread.Sleep(100);
     }
  }

  void ConsumerThread()
  {
    while (!done)
      {
        MyData d = (MyData)q.Dequeue();
        process(d);
      }
  }

消费者线程仅在队列中有东西要处理时才执行,并且在没有任何事情要做时不会浪费CPU时间轮询。

答案 2 :(得分:0)

使用每500毫秒触发一次的计时器,让计时器处理程序完成工作。计时器处理程序线程在线程池中运行。请在此处阅读:http://www.albahari.com/threading/part3.aspx#_Timers

System.Timers.Timer timer = new System.Timer(500);
timer.Elapsed += new System.Timers.ElapsedEventHandler (MyTimerHandler);
timer.Start();

private void TimerHandler(object sender, System.Timers.ElapsedEventArgs e)
{
    // optional - stop the timer to prevent overlapping events
    timer.Stop();
    // this is where you do your thing
    timer.Start();
}

答案 3 :(得分:0)

您可能想要下载并阅读Joe Albahari关于C#中线程的免费电子书。这是一个很好的介绍和参考。

Threading in C#