我有 2 节课:
public class A
{
private const int MAXCOUNTER = 100500;
private Thread m_thrd;
public event Action<string> ItemStarted;
public event Action<string> ItemFinished;
private void OnItemStarted(string name)
{
if (ItemStarted != null) ItemStarted(name);
}
private void OnItemFinished(string name)
{
if (ItemFinished != null) ItemFinished(name);
}
public A()
{
m_thrd = new Thread(this.Run);
m_thrd.Start();
}
private void Run()
{
for (int i = 0; i < MAXCOUNTER; i++)
{
OnItemStarted(i.ToString());
// some long term operations
OnItemFinished(i.ToString());
}
}
}
public class B
{
private Thread m_thrd;
private Queue<string> m_data;
public B()
{
m_thrd = new Thread(this.ProcessData);
m_thrd.Start();
}
public void ItemStartedHandler(string str)
{
m_data.Enqueue(str);
}
public void ItemFinishedHandler(string str)
{
if (m_data.Dequeue() != str)
throw new Exception("dequeued element is not the same as finish one!");
}
private void ProcessData()
{
lock (m_data)
{
while (m_data.Count != 0)
{
var item = m_data.Peek();
//make some long term operations on the item
}
}
}
}
我们在代码中还有其他地方
A a = new A();
B b = new B();
a.ItemStarted += b.ItemStartedHandler;
a.ItemFinished += b.ItemFinishedHandler;
- 那么,如果在工作
ItemFinished
的时候提出ProcessData()
来,会发生什么? - 我应该使用诸如
AutoResetEvent
让课堂A
等待课堂B
结束之类的东西ProcessData
吗? - 有必要用
lock
在ProcessData
吗? - 可以用 调用类
B
的线程m_thrd = new Thread(this.ProcessData);
吗?这里的事情让我感到困惑 - 在引发任何事件之前不会ProcessData
完成ItemStarted
(它不会导致第一次生成线程时B
已经完成的情况)?ItemStarted