3 回答

TA貢獻(xiàn)1828條經(jīng)驗 獲得超13個贊
因為Invoke/ BeginInvoke接受Delegate(而不是類型的委托),所以您需要告訴編譯器要創(chuàng)建什么類型的委托;MethodInvoker(2.0)或Action(3.5)是常見選擇(請注意,它們具有相同的簽名);像這樣:
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});
如果需要傳遞參數(shù),則可以使用“捕獲的變量”:
string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});
(注意:如果使用captures async,則需要謹(jǐn)慎一點,但是sync很好-即上述情況很好)
另一種選擇是編寫擴展方法:
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
然后:
this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });
當(dāng)然,您可以使用BeginInvoke:
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
如果不能使用C#3.0,則可以使用常規(guī)實例方法(大概是在Form基類中)執(zhí)行相同的操作。

TA貢獻(xiàn)1784條經(jīng)驗 獲得超9個贊
實際上,您不需要使用委托關(guān)鍵字。只需將lambda作為參數(shù)傳遞:
control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

TA貢獻(xiàn)1780條經(jīng)驗 獲得超5個贊
我對其他建議有疑問,因為我有時想從我的方法中返回值。如果您嘗試將MethodInvoker與返回值一起使用,則似乎不喜歡它。所以我使用的解決方案是這樣的(非常高興聽到一種使它更簡潔的方法-我正在使用c#.net 2.0):
// Create delegates for the different return types needed.
private delegate void VoidDelegate();
private delegate Boolean ReturnBooleanDelegate();
private delegate Hashtable ReturnHashtableDelegate();
// Now use the delegates and the delegate() keyword to create
// an anonymous method as required
// Here a case where there's no value returned:
public void SetTitle(string title)
{
myWindow.Invoke(new VoidDelegate(delegate()
{
myWindow.Text = title;
}));
}
// Here's an example of a value being returned
public Hashtable CurrentlyLoadedDocs()
{
return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
{
return myWindow.CurrentlyLoadedDocs;
}));
}
- 3 回答
- 0 關(guān)注
- 610 瀏覽
添加回答
舉報