【发布时间】:2012-07-23 20:50:38
【问题描述】:
我在 CodeProject 上找到了以下代码 sn-p 关于异步调用方法的... http://www.codeproject.com/Articles/14931/Asynchronous-Method-Invocation
private void CallFooWithOutAndRefParameters()
{
// create the paramets to pass to the function
string strParam1 = "Param1";
int intValue = 100;
ArrayList list = new ArrayList();
list.Add("Item1");
// create the delegate
DelegateWithOutAndRefParameters delFoo =
new DelegateWithOutAndRefParameters(FooWithOutAndRefParameters);
// call the beginInvoke function!
IAsyncResult tag =
delFoo.BeginInvoke(strParam1,
out intValue,
ref list,
null, null);
// normally control is returned right away,
// so you can do other work here...
// calling end invoke notice that intValue and list are passed
// as arguments because they might be updated within the function.
string strResult =
delFoo.EndInvoke(out intValue, ref list, tag);
// write down the parameters:
Trace.WriteLine("param1: " + strParam1);
Trace.WriteLine("param2: " + intValue);
Trace.WriteLine("ArrayList count: " + list.Count);
Trace.WriteLine("return value: " + strResult);
}
关于这段代码,我有几处不明白。
当注释控件到达 BeginInvoke 行时,它会立即返回给调用代码。
这是否意味着后面的代码(EndInvoke 后跟一些跟踪日志记录)仅在 FooWithOutAndRefParameters 调用完成后运行......自动(即使该代码驻留在同一方法中)。我看起来有点困惑。 (我一直使用回调来处理这种事情。)
使用此方法我必须调用 EndInvoke。我可以异步调用该方法并忘记它的发生吗?这样做有什么缺点吗?
如果我不调用 EndInvoke(如本方法所示),我是否应该总是有回调?即使回调什么也不做。
如果您应该回答...那么您是调用 EndInvoke 还是定义一个回调? (定义回调的好处是通知您结果)
顺便说一句,我知道我可以在 EndInvoke 或回调中检查错误或记录结果(实际上我可能会这样做)。我想知道的是是否存在不调用 EndInvoke 或定义回调(例如内存泄漏)的风险?最佳做法是什么。
赛斯
【问题讨论】:
-
虽然我回复了,但我认为它与stackoverflow.com/questions/4585042/…略有重复
标签: c# .net vb.net asynchronous callback