您现在的位置是:网站首页> 编程资料编程资料
.net让线程支持超时的方法实例和线程在执行结束后销毁的方法_实用技巧_
2023-05-24
330人已围观
简介 .net让线程支持超时的方法实例和线程在执行结束后销毁的方法_实用技巧_
.net让线程支持超时
使用 CancellationTokenSource
private static void TimeoutTest1()
{
var cts = new CancellationTokenSource();
var thread = new Thread(() =>
{
Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(10000);
Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
});
cts.Token.Register(() =>
{
thread.Abort();
});
cts.CancelAfter(1000);
thread.Start();
thread.Join();
Console.WriteLine(String.Format("线程{0}的状态:{1}", thread.ManagedThreadId, thread.ThreadState));
}
这里采用了 Abort 终止了线程,CancellationTokenSource 也支持其它模式,可以去官方看看文档。
使用 Join
private static void TimeoutTest2()
{
var thread = new Thread(() =>
{
Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(10000);
Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
});
thread.Start();
thread.Join(1000);
thread.Abort();
Console.WriteLine(String.Format("线程{0}的状态:{1}", thread.ManagedThreadId, thread.ThreadState));
}
.net让线程在执行结束后销毁
线程执行完、遇到未处理异常和被终止后就自动不可用了,如果是垃圾,自然会被 GC 给回收,有一点需要说明的是:线程的未处理异常会导致应用程序的终止,一个线程的异常不会自动冒泡到其它线程。
相关内容
- ASP.NET拒绝访问临时目录的解决方法_实用技巧_
- Asp.Net Couchbase Memcached图文安装调用开发_实用技巧_
- 使用Aspose.Cells组件生成Excel文件实例_实用技巧_
- 在Web用户控件中引用样式表中样式的方法_实用技巧_
- Asp.net调试的一些问题小结_实用技巧_
- log4net创建系统日志的详细步骤_实用技巧_
- net insert into语法错误详解_实用技巧_
- asp.net使用jQuery Uploadify上传附件示例_实用技巧_
- .net获取本机公网IP地址示例_实用技巧_
- Repeater控件与PagedDataSource结合实现分页功能_实用技巧_
