在C#中,BeginInvoke方法用于在另一個線程上異步執行一個方法。這個方法通常用于在UI線程上執行長時間運行的操作,以避免阻塞UI。BeginInvoke方法需要兩個參數:
MyMethod的方法,你可以使用Action或Func委托。public void MyMethod()
{
// Your code here
}
// Usage
BeginInvoke(new Action(MyMethod));
或者
public int MyMethod(int param)
{
// Your code here
return result;
}
// Usage
BeginInvoke(new Func<int, int>(MyMethod), paramValue);
public void AsyncCallback(IAsyncResult result)
{
// Your code here to handle the completion of the asynchronous operation
}
// Usage
BeginInvoke(new Action(MyMethod), null, AsyncCallback);
或者
public int AsyncCallback(IAsyncResult result)
{
// Your code here to handle the completion of the asynchronous operation
return resultValue;
}
// Usage
BeginInvoke(new Func<int, int>(MyMethod), paramValue, AsyncCallback);
請注意,BeginInvoke方法屬于Control類(例如,Button、TextBox等),因此你需要在一個控件上調用它。如果你需要在非控件類中使用BeginInvoke,你可以創建一個Control實例(例如,new Control()),然后在該實例上調用BeginInvoke。