阅读量:2
在C#中,当你使用Thread.Wait()方法时,可能会遇到中断异常。为了处理这种异常,你可以使用try-catch语句来捕获InterruptedException。下面是一个示例:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// 等待一段时间,然后中断线程
Thread.Sleep(2000);
thread.Interrupt();
// 等待线程完成
thread.Join();
}
static void DoWork()
{
try
{
Console.WriteLine("Thread started.");
Thread.Sleep(5000); // 模拟耗时操作
Console.WriteLine("Thread finished.");
}
catch (InterruptedException ex)
{
Console.WriteLine("Thread was interrupted: " + ex.Message);
// 在此处处理中断异常,例如设置标志位以通知其他代码线程已被中断
}
}
}
在这个示例中,我们创建了一个新线程并启动它。然后,我们让主线程等待2秒钟,之后中断新线程。DoWork方法中的try-catch语句捕获InterruptedException,我们可以在其中处理异常,例如设置一个标志位以通知其他代码线程已被中断。
以上就是关于“c# wait 怎样处理中断异常”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm