C# 總結QueueUserWorkItem傳參幾種方式案例詳解
最近在學習citrix的xenserver6.2的源代碼,發(fā)現多處用到System.Threading命名空間下的ThreadPool.QueueUserWorkItem方法:
public static bool QueueUserWorkItem(WaitCallback callBack, object state);
publicstaticbool QueueUserWorkItem(WaitCallback callBack);
參數WaitCallback 本身是一個delegate,它在System.Threading命名空間中的定義如下:
[ComVisible(true)] public delegate void WaitCallback(object state);
于是問題來了,該如何給QueueUserWorkItem傳參呢?以下是我遇到的一些方式:
1,直接傳delegate。(不明白object o去了哪里?)
ThreadPool.QueueUserWorkItem(delegate
{
for (int i = 0; i < 20 && TargetNode.Nodes.Count == 0; i++)
{
Thread.Sleep(100);
}
MainWindowCommandInterface.Invoke(delegate { TargetNode.Expand(); });
});
2,直接傳方法名。
ThreadPool.QueueUserWorkItem(WaitForReboot, connection);
private void WaitForReboot(object o)
{
}
3,用delegate構造一個WaitCallback。
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(Object o)
{
ClientFillRectangle(0, 0, DesktopSize.Width, DesktopSize.Height, Color.Black);
}), null);
4,用含一個object類型的方法Connect構造一個WaitCallback。
ThreadPool.QueueUserWorkItem(new WaitCallback(Connect), new KeyValuePair<VNCGraphicsClient, Exception>(vncClient, null));
private void Connect(object o)
{
}
5,WaitCallback類型的delegate。
ThreadPool.QueueUserWorkItem((WaitCallback)delegate(object o)
{
// Sleep a short time before closing the splash
Thread.Sleep(500);
Program.Invoke(Program.MainWindow, Program.CloseSplash);
});
6,直接傳Lambda表達式。
ThreadPool.QueueUserWorkItem(o =>
{
Program.Invoke(Program.MainWindow, () =>
{
PerformStorageSystemScan();
if (systemsAfter.Count > systemsBefore.Count)
{
// the new item should be selected
. comboBoxStorageSystem.SelectedItem = systemsAfter.Find(ss => !systemsBefore.Contains(ss));
comboBoxStorageSystem.DroppedDown = true;
}
});
});
到此這篇關于C# 總結QueueUserWorkItem傳參幾種方式案例詳解的文章就介紹到這了,更多相關C# 總結QueueUserWorkItem傳參幾種方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

