如何防止 System.Timers.Timer 在停止后引发 Elapsed 事件?
我有以下代码:
using (FileStream sourceStream = sourceFile.Open())
{
using (FileStream targetStream = File.Create(targetFilePath))
{
using (Timer timer = new Timer(250))
{
timer.Elapsed += (sender, e) =>
{
if (this.FileCopyProgressChanged != null)
{
//Here the ObjectDisposedException appears
this.FileCopyProgressChanged(this,
new CopyProgressEventArgs(
sourceStream.Length,
targetStream.Length));
}
};
timer.Start();
sourceStream.CopyTo(targetStream);
timer.Stop();
}
}
}
我的计时器每 250 毫秒计时一次,并引发一个事件,其中包含有关流复制进度的信息。 问题是,有时在计时器事件中,会抛出 ObjectDisposeException,因为流不再打开。
如何防止我的计时器在我的流被处理后引发已用事件?
I have the followig code:
using (FileStream sourceStream = sourceFile.Open())
{
using (FileStream targetStream = File.Create(targetFilePath))
{
using (Timer timer = new Timer(250))
{
timer.Elapsed += (sender, e) =>
{
if (this.FileCopyProgressChanged != null)
{
//Here the ObjectDisposedException appears
this.FileCopyProgressChanged(this,
new CopyProgressEventArgs(
sourceStream.Length,
targetStream.Length));
}
};
timer.Start();
sourceStream.CopyTo(targetStream);
timer.Stop();
}
}
}
My timer elapses every 250 milliseconds and raises an event with information about the stream copy progress.
The problem is, that sometimes in the timer event, a ObjectDisposedException gets thrown, because the streams are not opened anymore.
How can I prevent my timer from raising the elapsed event after my streams are disposed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不直接这样做,不需要计时器:
Why not just do this, no timers required: