软件在处理IO任务时,需要使用多线程,提高效率。 但在资源准备好了以后,需要使用单线程,来简化控制逻辑,避免不必要的lock语句或原子代码。以下代码是C#中生产者消费者的一种变种使用方式,用于完成上诉任务。无守候线程,逻辑简单::
/// <summary>
/// 生产,消费者 控制代码
/// 生产者考虑为多线程.
/// 消费者必须是单线程执行。
/// </summary>
public class ProviderConsumer
{
uint syncID = 0;
Action toCall;
object m_lock = new object();
/// <summary>
/// 有新的资源写入,需要处理
/// </summary>
public void NewResource()
{
syncID++;
CheckRuning();
}
/// <summary>
/// 消费者函数注册
/// </summary>
/// <param name="callback"></param>
public void RegistConsumer(Action callback)
{
if (toCall == null)
toCall = callback;
else
throw new Exception("不能修改消费函数");
}
void CheckRuning()
{
lock (m_lock)
{
if (toCall == null)
return;
//不使用阻塞变量,以销毁线程。
Action f = DoFuncCall;
f.BeginInvoke(null, null);
}
}
void DoFuncCall()
{
Action Func = null;
try
{
lock (m_lock)
{
if (this.toCall == null)
return;
Func = toCall;
toCall = null;
}
uint syncIN = this.syncID - 1;
while (syncID != syncIN)
{
syncIN = syncID;
Func();
}
}
finally
{
if (Func != null)
this.toCall = Func;
}
}
}