【发布时间】:2012-06-11 16:31:56
【问题描述】:
最近我遇到越来越多的人编写类似以下代码:
private AsynchronousReader r;
public SynchronousReader()
{
r = new AsynchronousReader();
// My practice is to put this here
// and then never remove it and never add it again
// thus cleaning up the code and preventing constant add/remove.
//r.ReadCompleted += this.ReadCompletedCallback;
}
private ReadCompletedCallback()
{
// Remove the callback to "clean things up"...
r.ReadCompleted -= this.ReadCompletedCallback;
// Do other things
}
public Read()
{
r.ReadCompleted += this.ReadCompletedCallback;
// This call completes asynchronously and later invokes the above event
r.ReadAsync();
r.WaitForCompletion();
}
人们说这种做法比我上面指出的要好,并给出了 Silverlight 特有的几个原因。他们说它可以防止内存泄漏、线程问题,甚至是正常的做法。
我没有做过多少 Silverlight,但仍然这样做似乎很愚蠢。 是否有任何具体原因可以使用此方法,而不是在构造函数中一次性装配回调并在对象的生命周期内完成?
这就像我的例子一样简单。忽略它是一种将异步对象转换为同步对象的包装器这一事实。我只是对添加和删除事件的方式感到好奇。
【问题讨论】:
标签: c# silverlight events