如何阻止我的System.Timers.Timer在停止后引发Elapsed事件?

时间:2011-04-12 06:39:07

标签: c# timer thread-safety objectdisposedexception

我有以下代码:

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毫秒过一次并引发一个事件,其中包含有关流复制进度的信息。 问题是,有时在计时器事件中,会抛出ObjectDisposedException,因为流不再打开。

如何防止我的计时器在我的流被丢弃后引发已经过的事件?

1 个答案:

答案 0 :(得分:3)

为什么不这样做,不需要计时器:

using (FileStream sourceStream = sourceFile.Open())
{
    using (FileStream targetStream = File.Create(targetFilePath))
    {
        int bytesTotal = sourceStream.Length;
        int bytesCurrent = 0;
        var buffer = new byte[32*1024];
        int bytes;
        while ((bytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            targetStream.Write(buffer, 0, bytes);
            bytesCurrent += bytes;
            FileCopyProgressChanged(this,
                new CopyProgressEventArgs(bytesTotal, bytesCurrent));
        }
    }
}