.NET - 线程同步
我一直在开发一个线程,只要应用程序正在运行,该线程就会存在,并且以 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
.NET/C# 最佳实践是使用 EventWaitHandle。
您将在线程之间共享一些变量,如下所示:
)中,您将循环等待句柄(可能有超时):
在消费者线程(您现在每 500 毫秒唤醒一次的线程 生产者线程:
.NET/C# best practice would be to use an EventWaitHandle.
You'd have some variable shared between the threads as so:
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):
And in the producer thread:
也许您可以使用阻塞队列:http://www.eggheadcafe.com/articles/20060414。 asp
它是一个队列,除了 Dequeue 函数会阻塞,直到有一个对象要返回。
用法:
消费者线程仅在队列中有东西需要处理时才执行,无事可做时不会浪费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:
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.
使用每 500 毫秒触发一次的计时器,并让您的计时器处理程序完成工作。定时器处理程序线程在线程池中运行。在这里阅读:http://www.albahari.com/threading/part3.aspx #_定时器。
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.
您可能想下载并阅读 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#