System.Threading.Timer 使用问题!!

eclipse_jhd 2008-08-29 06:17:12
System.Threading.Timer[] threadTimers = null;
threadTimers = new System.Threading.Timer[dsClientList.Tables[0].Rows.Count];
//GC.KeepAlive(threadTimers);
foreach (DataRow drow in dsClientList.Tables[0].Rows)
{
KkInfor infor = new KkInfor();
infor.kkip = drow["IP"].ToString();
infor.kkconstr = drow["ConnectionString"].ToString();
infor.kkname = drow["Name"].ToString();
threadTimers[count] = new System.Threading.Timer(new TimerCallback(Excetu), infor, 0, 2000);
GC.KeepAlive(threadTimers[count]);
}

public void Excetu(object kk)
{

Console.WriteLine(((KkInfor)kk).kkbh, ((KkInfor)kk).kkconstr, ((KkInfor)kk).kkconstr);
}
--------------------------
我定义一个线程定时器数组,执行一组不同的任务。
但是问题是线程组隔一段时间后就被垃圾回收了。必须GC.KeepAlive来保持线程组不被垃圾回收器回收。
就是这样隔一段时间后就有一个定时器不再执行。
...全文
183 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzultc 2008-08-31
  • 打赏
  • 举报
回复
关键在于你的线程函数吧?
你的TimerCallback是个临时变量,很容易被GC回收。
你把TimerCallback添加一个全局静态引用或者其他的引用,试一下。
eclipse_jhd 2008-08-30
  • 打赏
  • 举报
回复
特点?
什么意思!
li45214521 2008-08-30
  • 打赏
  • 举报
回复
这个好像不是问题吧
是特点吧
eclipse_jhd 2008-08-29
  • 打赏
  • 举报
回复
System.Threading.Timer[] threadTimers = null;
我没有放在方法里面,是放在类里,并且是static类型的。
但是结果是一样的。
jzywh 2008-08-29
  • 打赏
  • 举报
回复
System.Threading.Timer[] threadTimers = null;
不要放到方法里面, 要直接放到类里面作为类的成员, 否则这些timer的舍命周期只能在方法内了

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧