c# 在timer里不能控制其他线程终止吗?
我在线程内创建一个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());
}
}
}
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());
}
}
}
...全文
相关推荐
C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
**System.Threading.Timer是最灵活的Timer,因为它允许在任何线程上运行,且提供了更多的控制选项。
C#_Timer及多线程编程
### Timer与其他Timer类的区别除了`System.Windows.Forms.Timer`外,C#还提供了其他两种类型的计时器:1.
C#中DispatcherTimer VS Timer
在选择计时器时,需要考虑以下几点:* 是否需要在同一个线程中访问用户界面元素?* 是否需要在多线程环境中使用?* 是否需要指定计时器的执行优先级?
细细品味C#(Timer及多线程编程).pdf
另外,C#还提供了volatile关键字,该关键字用于表示变量可能在程序的控制范围之外被修改,指示编译器不要对变量的操作进行重排序优化。
Timer及多线程编程
#### 并发控制除了上述技术外,C#还提供了`lock`语句、`volatile`关键字、`Interlocked`类等来帮助开发者编写线程安全的代码。


