C# using a timer inside a Backgroundworker

血红的双手。 提交于 2019-12-06 04:40:20

Use a Stopwatch and check within the while loop the Elapsed property. That way you prevent from concurrent writing and closing the same file.

From a design perspective I would separate the concerns of writing and splitting into files. You may want to look into the source code of log4net (NLog?) since they have implementations of rolling file appenders, since you may have to be careful about not messing up by losing some data.

You could use a Threading.Timer like so

private static void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e)
{
    var timer = new Timer(x => 
    {
       lock (file)
       {
          // close old file and open new file                    
       }
    }, null, 0, (int)e.Argument);

    while(true)
    {
        if (bckWrkSocket.CancellationPending) { e.Cancel = true; return; }
        // check socket etc. 
    }
}

Define a global variable which store timer tick count.

 int timerCount = 0;

-

private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e)
{
     timer.Tick += new EventHandler(TimerEventProcessor);

     // Sets the timer interval to 1 minute.
     timer.Interval = 60000;
     timer.Start();
}

-

public void TimerEventProcessor(Object myObject,
                                        EventArgs myEventArgs) {

     if(timerCount % 2 == 0)
         //Do you works

     timerCount++;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!