场景:由于保存图片需要耗时等待,需要加入多线程队列的形式缓存每次的请求,确保每次请求过来都能可靠的进行保存 private static Queue<Func<int>> m_List; private static object m_obj = new object(); private bool isExit = false;
#region 任务队列
public Func<int> Pop()
{
Monitor.Enter(m_obj);
//Action ac = null;
Func<int> ac = null;
try
{
if (m_List.Count > 0)
{
ac = m_List.Dequeue();
}
else
{
//Monitor.Wait(m_obj);
//ac = m_List.Dequeue();
}
}
finally
{
Monitor.Exit(m_obj);
}
return ac;
}
public void Push()
{
Monitor.Enter(m_obj);
Func<int> fuc = new Func<int>(ImgSave);
m_List.Enqueue(fuc);
Monitor.Pulse(m_obj);
Monitor.Exit(m_obj);
}
public void ThreadWork()
{
while (!isExit)
{
Func<int> work = Pop();
try
{
if (work != null)
{
work();
}
else
{
break;
}
}
catch (Exception)
{
Console.WriteLine("error..");
return;
}
}
Console.WriteLine("exit threadWork");
}
#endregion
private int ImgSave()
{
#region 保存图片
stopWatch.Start();
Console.WriteLine("save....");
DateTime dtNow = System.DateTime.Now; // 获取系统当前时间
string strDateTime = dtNow.Year.ToString() + "_"
+ dtNow.Month.ToString().PadLeft(2, '0') + "_"
+ dtNow.Day.ToString().PadLeft(2, '0') + "_"
+ dtNow.Hour.ToString().PadLeft(2, '0') + "_"
+ dtNow.Minute.ToString().PadLeft(2, '0') + "_"
+ dtNow.Second.ToString().PadLeft(2, '0') + "_"
+ dtNow.Millisecond.ToString().PadLeft(3, '0');
// 文件命名规则
string stfFileName = strDateTime + ".png"; // 默认的图像保存名称
//ImagePersistence.Save(ImageFileFormat.Png, stfFileName, grabResult);
Image bitmap = pictureBox.Image;
ImgHelper.GetPicThumbnail(bitmap, stfFileName, bitmap.Height, bitmap.Width, 70);
stopWatch.Stop();
Console.WriteLine("Save end...." + stopWatch.Elapsed);
showMsg("img save end >>" + stfFileName);
return 0;
#endregion
}
执行调用
private void button1_Click(object sender, EventArgs e)
{
Push();
th = new Thread(new ThreadStart(ThreadWork));
th.Start();
Console.WriteLine("add task complete.");
}