c# 多線程控制的方法有很多種,然而如何優雅地控制多線程卻是門學問。筆者一直也糾結於此,失敗的多線程設計絕對是畫虎不成反類貓,不但沒有提高性能,效率反而會更低。
下面的一段代碼使用了信號量對多線程進行控制,希望讀到的朋友能體會到優雅的代碼所帶來的樂趣。也希望高手們提供更高明的方法。
using System;
using System.Threading;
namespace MyLab
{
public delegate void handler(object obj);
public class Program
{
/// <summary>
/// 信號量用於控制最大並發線程數
/// </summary>
private static Semaphore pool;
/// <summary>
/// 用於控制暫停、繼續
/// </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 = _num;
pool = new Semaphore(0, _num);
Thread t = new Thread(delegate() { Run(); });
t.Start();
}
public void Pause()
{
bPause = true;
status.Reset();
}
public void Resume()
{
bPause = false;
status.Set();
}
public void Stop()
{
status.Reset();
bStoped = true;
}
}
}