在.NET中,BeginInvoke
用于异步调用委托,而正确结束异步操作需要调用EndInvoke
以确保资源释放和结果获取。以下是完整说明:
BeginInvoke
启动异步调用,返回IAsyncResult
对象。EndInvoke
阻塞调用线程,直到异步操作完成,并返回委托的返回值(如有)。public delegate int MyDelegate(string input);
public int MyMethod(string input) { return input.Length; }
// 异步调用
MyDelegate del = MyMethod;
IAsyncResult asyncResult = del.BeginInvoke("test", null, null);
// ...其他操作...
// 必须调用EndInvoke
int result = del.EndInvoke(asyncResult); // 阻塞直到完成
public delegate int MyDelegate(string input);
public int MyMethod(string input) { return input.Length; }
// 回调函数
AsyncCallback callback = ar => {
MyDelegate del = (MyDelegate)ar.AsyncState;
int result = del.EndInvoke(ar); // 必须在回调中调用EndInvoke
Console.WriteLine(result);
};
// 异步调用并传递委托作为状态
MyDelegate del = MyMethod;
del.BeginInvoke("test", callback, del);
EndInvoke
以避免资源泄漏(如线程、内存等)。EndInvoke
可能导致内存泄漏或未处理的异常。EndInvoke
会阻塞调用线程,若需非阻塞,需结合回调或async/await
(.NET 4.5+)。EndInvoke
时抛出,需用try-catch
捕获:EndInvoke
时抛出,需用try-catch
捕获:使用Task
或async/await
更简洁:
public async Task<int> MyMethodAsync(string input) {
return await Task.Run(() => input.Length);
}
// 调用
var result = await MyMethodAsync("test");
EndInvoke
导致资源泄漏。
解决:确保所有BeginInvoke
都有对应的EndInvoke
。try-catch
。Control.Invoke
(WinForms)或Dispatcher.Invoke
(WPF)。