在计时器回调中创建的线程意外终止
这就是我想要做的:
- 有一个具有一定间隔的计时器
- 在计时器回调代码中,如果满足某些条件,则应该运行另一个线程
我已将代码放入一个由主窗体和代码实例化的类中在方法调用时执行(“StartSync()”,参见示例代码)。
问题是代码运行了几秒钟,然后终止。我想我在做一些愚蠢的事情,但我真的不明白那是什么。感谢您对此提供的任何帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
class Syncer
{
static bool SYNC_IN_PROGRESS;
public void StartSync()
{
SYNC_IN_PROGRESS = false;
Timer timer = new Timer(timerCallback, null, 0, 1000);
}
public void timerCallback(Object stateInfo)
{
Debug.WriteLine("Sync?");
if (!SYNC_IN_PROGRESS)
{
SYNC_IN_PROGRESS = true;
Thread thSync = new Thread(new ThreadStart(sync));
thSync.Start();
}
}
void sync()
{
Debug.WriteLine("Syncing...");
SYNC_IN_PROGRESS = false;
}
}
}
This is what I want to do:
- Have a timer with some interval
- In the timer callback code, if some condition is met, another thread should be run
I’ve put my code in a class which is instantiated by the main form and the code is executed upon method call (‘StartSync()’, se sample code).
The problem is that the code runs for a couple of seconds but then terminates. I suppose I’m doing something stupid but I really can’t see what it is. Thankful for any help with regards to this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
class Syncer
{
static bool SYNC_IN_PROGRESS;
public void StartSync()
{
SYNC_IN_PROGRESS = false;
Timer timer = new Timer(timerCallback, null, 0, 1000);
}
public void timerCallback(Object stateInfo)
{
Debug.WriteLine("Sync?");
if (!SYNC_IN_PROGRESS)
{
SYNC_IN_PROGRESS = true;
Thread thSync = new Thread(new ThreadStart(sync));
thSync.Start();
}
}
void sync()
{
Debug.WriteLine("Syncing...");
SYNC_IN_PROGRESS = false;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
猜测,
Timer
仅保存在方法变量中; 对我来说听起来就像Timer
正在收集垃圾并最终确定,因此终止。我怀疑您应该在字段中保留该引用以防止收集。顺便说一句 - 我怀疑这是这里的原因,但是在处理线程时,您应该认真地意识到从多个线程访问共享状态;例如:
Monitor
(又名lock
)易失性
您当前访问的
Interlocked
static bool
可能可以正常工作,但是......At a guess, the
Timer
is only held in a method variable; it sounds to me like theTimer
is getting garbage collected and finalized, hence terminated. I suspect you should hold onto that reference in a field to prevent collection.As an aside - I doubt it is the cause here, but when dealing with threading you should be religiously aware of access to shared state from multiple threads; for example:
Monitor
(akalock
)volatile
Interlocked
when it fitsYour current access to the
static bool
will probably work OK, but...尝试这种更干净的方法
它的作用与您尝试对当前代码执行的操作相同:)但不使用计时器
Try this cleaner approach
It does the same you try to do with your current code :) but doesn't use a timer
这就是我所做的,看起来效果很好
So here is what I did and it seems to work just fine