c# - How can I prevent my System.Timers.Timer from raising the Elapsed event after it got stopped? -


i have 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 objectdisposedexception appears                     this.filecopyprogresschanged(this,                         new copyprogresseventargs(                             sourcestream.length,                             targetstream.length));                 }             };              timer.start();              sourcestream.copyto(targetstream);              timer.stop();         }     } } 

my timer elapses every 250 milliseconds , raises event information stream copy progress. problem is, in timer event, objectdisposedexception gets thrown, because streams not opened anymore.

how can prevent timer raising elapsed event after streams disposed?

why not this, no timers required:

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));         }     } } 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -