使用定时器一个BackgroundWorker内的C# [英] C# using a timer inside a Backgroundworker
问题描述
我无法找到一个解决方案尚未...希望有人能帮助我。
我有一个运行,直到它被用户取消一个BackgroundWorker (它从插座中读取数据并将其写入到一个文件中)。
现在我想的时间,例如在一段时间后的输出文件分割每2分钟创建一个新的文件。
要做到这一点,我想用一个定时器,像
私人无效bckWrkSocket_DoWork(对象发件人,DoWorkEventArgs E)
{
//创建定时器并设置其为e.Argument
//发车间隔定时器
,而(真)
{
如果(timer.finished ==真)
{
//关闭旧文件并创建新的
//重新启动定时器
}
:
}
}
任何建议/想法
编辑:秒表做的伎俩。这里是我的解决方案
这里是我的解决方案:
私人无效bckWrkSocket_DoWork(对象发件人,DoWorkEventArgs E)
{
长targettime =(长)e.Argument;
秒表手表=新的秒表();
如果(targettime大于0)
watch.Start();
,而(真)
{
如果((targettime大于0)及及(watch.ElapsedMilliseconds> = targettime))
{
..
watch.Reset();
watch.Start();
}
}
使用一个秒表和while循环中检查经过的财产。这样,你的写作并发和关闭相同的文件阻止。
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) && (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.
这篇关于使用定时器一个BackgroundWorker内的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!