我正在尝试使用WaitCallback将字典列表传递给新线程,但我无法使其正常工作。这是p
Dictionary<string, string> iRequestObjects = new Dictionary<string, string>();
iRequestObjects.Add("Query String", queryString );
iRequestObjects.Add("Item2", "ItemData");
ThreadPool.QueueUserWorkItem(new WaitCallback(iLogEventSave),iRequestObjects);
public void iLogEventSave(object state, IDictionary<object, object> dObject)
{
}
答案 0 :(得分:2)
虽然你可以修改你的代码以适当地传递状态,如其他答案所述,我发现使用闭包将数据传递给将用于启动新的委托通常要容易得多。线程,至少除非有一些令人信服的理由不这样做:
ThreadPool.QueueUserWorkItem(s => iLogEventSave(iRequestObjects));
然后你的方法可以拥有你想要的签名:
public void iLogEventSave(IDictionary<string, string> state)
答案 1 :(得分:0)
示例:
static void MyCallBack(object stateInfo)
{
IDctionary<object, object> dict = (IDictionary<object, object>)stateInfo;
}
请点击此处了解更多信息:
http://msdn.microsoft.com/en-us/library/4yd16hza(v=vs.110).aspx
答案 2 :(得分:0)
WaitCallback
定义为public delegate void WaitCallback(Object state)
。因此,您需要做的是将传递给state
的{{1}}对象转换为state
传递给QueueUserWorkItem
的对象。
Dictionary<string, string> iRequestObjects = new Dictionary<string, string>();
iRequestObjects.Add("Query String", queryString );
iRequestObjects.Add("Item2", "ItemData");
ThreadPool.QueueUserWorkItem(new WaitCallback(iLogEventSave),iRequestObjects);
public void iLogEventSave(object state)
{
IDictionary<object, object> dObject = (IDictionary<object, object>)state;
}
注意,如果您执行此操作,则会收到InvalidCastException
,因为Dictionary<string, string>
无法投放到IDictionary<object, object>
。
您有几个选择:
iRequestObjects
更改为Dictionary<object, object>
dObject
更改为IDictionary<string, string>
dObject
改为IDictonary
而不是IDictionary<object, object>