c# 在timer里不能控制其他线程终止吗?

抚落霞 抚落霞 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在线程内创建一个timer来控制线程本身,但是发现在timer里不能控制线程终止。谢了个小测试:
class Program
{
static void Main(string[] args)
{
Test t = new Test();
Console.ReadLine();
}
}
class Test
{
public Thread a;
public Test()
{
a = new Thread(new ThreadStart(test));
a.Start();
}
int i = 0;
private void test()
{

System.Timers.Timer ab = new System.Timers.Timer();
ab.Interval = 1000;
ab.Elapsed += delegate
{
if (i > 5)
{
if (a.IsAlive) { a.Abort(); Console.WriteLine("线程已执行停止!"); }
if (a.IsAlive) { Console.WriteLine("线程仍未停止!"); }
}
ab.Stop();
ab.Dispose();
};
ab.Start();
while (true)
{
i++;
Console.WriteLine(i.ToString());
}
}
}
...全文

相关推荐

评论 30
收藏 已收藏
分享
返回顶部
抚落霞
C# 111,128 成员 642,537 内容