【发布时间】:2015-08-15 08:01:31
【问题描述】:
我有 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;
- 那么,如果在
ProcessData()仍在工作时引发了ItemFinished,会发生什么? - 我应该使用
AutoResetEvent之类的东西来让A等课程B完成ProcessData? -
lock必须在ProcessData中使用吗? - 可以用
m_thrd = new Thread(this.ProcessData);调用B类的线程吗?这件事让我感到困惑 - 在引发任何ItemStarted事件之前,ProcessData不会完成(当ItemStarted第一次生成时,B中的线程已经完成,这不会导致这种情况吗)?
【问题讨论】:
标签: c# multithreading locking semaphore autoresetevent