开发者

C# using a timer inside a Backgroundworker

开发者 https://www.devze.com 2023-04-08 11:54 出处:网络
I couldn\'t find a solution for this yet...hope someone can help me. I have a backgroundworker that runs until it is cancelled by the user (it reads data from a socket and writes it into a file).

I couldn't find a solution for this yet...hope someone can help me.

I have a backgroundworker that runs until it is cancelled by the user (it reads data from a socket and writes it into a file).

Now I want to split the output file after a certain period of time, e.g. every 2 mins create a new file.

For this to happen I'd like to use a timer, something like

private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e)
{
//create timer and set its interval to e.Argument
//start timer

while(true)
{
    if(timer.finished == true)
    {
    //close old file and create new
    //restart timer
    }
 ...
}
}

Any suggestions / ideas?

edit: Stopwatch did the trick. Here's my solution Here's my solution:

private void bckWrkSocket_DoWork(object sender, DoWorkEventArgs e)
{
long targettime = (long) e.Argument;
Stopwatch watch = new Stopwatch();
if (targettime > 0)
            watch.Start();
while(true)
{
    if ((targettime > 0) &a开发者_如何学Pythonmp;& (watch.ElapsedMilliseconds >= targettime))
    {
    ...
    watch.Reset();
    watch.Start();
    }
}


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++;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号