从事件处理程序运行自自杀线程

发布于 2024-12-04 23:10:33 字数 218 浏览 0 评论 0原文

我对多线程和 C# 非常陌生,我必须解决这个问题: 我有经常触发的事件处理程序(必须这样做,因为事件处理程序调用是从 dll 调用的) 当调用处理程序方法时,我需要创建并运行一个线程,该线程将执行一些操作,其处理时间可能从几毫秒到几秒不等,当完成工作时,它会自行终止。当它完成时,evenhandler 可以创建另一个线程。同时创建的线程正在运行,不能从事件处理程序创建和运行其他线程。

非常感谢您的帮助。

I am very new to multi threading and c#, I have to solve this probelm:
I have event handler which is fired pretty often (it must be done that way, because event handler calls are invoked from the dll)
When handler method is invoked, I need to create and run one thread which will do some stuff and its processing can vary from few millisconds to few seconds, when finishes its work it kills itself. When it's finished, evenhandler can create another thread. Meanwhile created thread is running, no other threads can be created and runned from eventhandler.

Many thanks for help.

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

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

发布评论

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

评论(2

梦归所梦 2024-12-11 23:10:33

这一切听起来都很复杂,而且我不太清楚你实际上想要做什么,但听起来使用一个额外的线程和共享队列会更好地处理这个问题工作项。您的事件处理程序只需将另一个工作项添加到队列中,线程将从队列中选取项目并一次处理它们。

.NET 4 通过 BlockingCollection 使这一切变得简单 类型。当然,在 .NET 4 之前它仍然可行,但您需要找到第三方线程安全的生产者/消费者队列或自己编写一个。

This all sounds pretty complicated, and I don't have a good sense of what you're actually trying to do, but it sounds like this would be better handled with a single extra thread and a shared queue of work items. Your event handler would just add another work item to the queue, and the thread would pick items off the queue and process them one at a time.

.NET 4 makes this easy with the BlockingCollection<T> type. Before .NET 4 it's still doable of course, but you'll need to find a third-party thread-safe producer/consumer queue or write one yourself.

辞慾 2024-12-11 23:10:33

自杀的线程会带来问题。当线程确实杀死自己时,您必须与主线程同步。

在我看来,使用一个专用线程来完成这项工作似乎会更好。使用阻塞队列并实现生产者/消费者模式。不要在线程无事可做时杀死该线程,而是让它闲置,直到有更多工作到来。

Threads that kill themselves present problems. You have to synchronise with the main thread when the thread does kill itself.

It sounds to me as though you would be better off with a single dedicated thread that did the work. Use a blocking queue and implement the producer/consumer pattern. Rather than kill the thread when it has nothing to do, let it sit idle until more work arrives.

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