.NET - 线程同步

发布于 2024-08-18 04:15:22 字数 506 浏览 6 评论 0原文

我一直在开发一个线程,只要应用程序正在运行,该线程就会存在,并且以 500 毫秒的间隔运行。我注意到,如果队列中没有任何内容可供处理,我可能会毫无用处地进行处理,因此我四处查看了本地的一些资源,并找到了一个与我的示例接近的示例,但它是用 Java 编写的。

这个例子是这样的:

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

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

线程有这个来通知等待:

synchronized(this) {
    notifyAll();
}

这是在排队线程内。 我还希望您注意该类继承了 Runnable。

谁能快速解释一下C#中的相应函数吗?如果可以的话也许可以举个例子!

I've been working on a thread which will live as long as the application is running, and runs at a interval of 500ms. I noted that I could be uselessly processing if there's nothing in the queue for it to process, so I went around looking at some sources I had locally, and I found an example close to mine, but it's in Java.

The example had this:

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

Inside a while loop which goes on forever.

The thread has this to notify the wait:

synchronized(this) {
    notifyAll();
}

This was inside the enqueue thread.
I'd also like you to note that the class inherits Runnable.

Could anyone quickly explain the corresponding functions in C#? And maybe an example if you could!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黑凤梨 2024-08-25 04:15:22

.NET/C# 最佳实践是使用 EventWaitHandle

您将在线程之间共享一些变量,如下所示:

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

)中,您将循环等待句柄(可能有超时):

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

在消费者线程(您现在每 500 毫秒唤醒一次的线程 生产者线程:

produceSomething();
handle.Set();

.NET/C# best practice would be to use an EventWaitHandle.

You'd have some variable shared between the threads as so:

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

In the consumer thread (the one that you're waking up every 500ms right now), you'd loop waiting for the handle (perhaps with a timeout):

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

And in the producer thread:

produceSomething();
handle.Set();
情绪失控 2024-08-25 04:15:22

也许您可以使用阻塞队列: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时间轮询。

Maybe you can use a blocking queue : http://www.eggheadcafe.com/articles/20060414.asp

It's a Queue except Dequeue function blocks until there is an object to return.

Usage:

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);
      }
  }

The consumer thread only executes when there is something in the queue to process, and doesn’t waste CPU time polling when there is nothing to do.

蓝色星空 2024-08-25 04:15:22

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

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();
}

Use a timer that fires every 500ms and let your timer handler do the work. Timer handler threads run in the thread pool. Read about it here: 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();
}
寄离 2024-08-25 04:15:22

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

C# 中的线程

You might want to download and read Joe Albahari's free ebook on threading in C#. It's a great introduction and reference.

Threading in C#

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文