Article
c# 多线程代码之美设计与应用
2011/7/26 13:27:32
# 多线程控制的方法有很多种,然而如何优雅地控制多线程却是门学问。笔者一直也纠结于此,失败的多线程设计绝对是画虎不成反类猫,不但没有提高性能,效率反而会更低。
下面的一段代码使用了信号量对多线程进行控制pdf,希望读到的朋友能体会到优雅的代码所带来的乐趣。也希望高手们提供更高明的方法。
using System;
using System.Threading;
namespace MyLab
{
public delegate void handler(object obj);
public class Program
{
/// <summary>
/// pdf信号量用于控制最大并发线程数
/// </summary>
private static Semaphore pool;
/// <summary>
/// pdf用于控制暂停、继续
/// </summary>
private static ManualResetEvent status;
private static int count = 0;
private static int num = 50;
public Program()
{
status = new ManualResetEvent(false);
}
public static void QueueWorkItem(handler ihandler, object args)
{
Thread t = new Thread(delegate()
{
runThread(ihandler, args);
});
count++;
t.Name = string.Format("thread {0}", count);
t.Start();
}
public static void runThread(handler ihandler,object arg)
{
status.WaitOne();
pool.WaitOne();
ihandler(arg);
do
{
status.WaitOne();
if (bStoped)
{
Thread.CurrentThread.Abort();
}
}
while (bPause);
pool.Release();
}
public static void Main()
{
Application.Run(new Form1());
}
public static bool bStart = false;
public static bool bStoped = false;
public static bool bPause = false;
public static void Run()
{
if (bStart)
{
pool.Release(num);
status.Set();
bStart = false;
}
}
public void Start(int _num)
{
bStart = true;
num = _numpdf;
pool = new Semaphore(0, _num);
Thread t = new Thread(delegate() { Run(); });
t.Start()pdf;
}
public void Pause()
{
bPause = true;
status.Reset();
}
public void Resume()
{
bPause = false;
status.Set();
}
public void Stop()
{
status.Reset();
bStoped = true;
}
}
}