我已经寻找解决方案,但是没有发现任何有用的信息。
在某些类中,我有事件(event)。
public class ClassWithEvent
{
public event Action<string> SomeEvent;
...
}
这个事件有订阅者
public class SubscriberClass
{
public void SomeMethod(string value)
{
...
}
}
ClassWithEvent objectWithEvent = new ClassWithEvent();
SubscriberClass subscriberObject = new SubscriberClass();
objectWithEvent.SomeEvent += subscriberObject.SomeMethod;
在主线程中的某个位置可以调用此事件。
if(SomeEvent != null)
SomeEvent(someString);
当它发生时,它的处理程序必须在第二个线程中运行。但每次都在同一个线程中,因此这个第二个线程必须是永久的,并且在第一次执行后不会被终止。
请帮我实现这个。
while
循环,更简单的方法是使用foreach (string someValue in queue.GetConsumingEnumerable()) { //Do stuff }
。它的行为与您的版本相同,除了在多个消费者环境中,Take()
可能会在已经完成的集合上被调用而导致竞争情况。Take()
会抛出异常,而GetConsumingEnumerable()
则仅退出foreach
循环。 - Scott Chamberlain