c# wait 怎样处理中断异常
导读:在C#中,当你使用Thread.Wait( 方法时,可能会遇到中断异常。为了处理这种异常,你可以使用try-catch语句来捕获InterruptedException。下面是一个示例: using System; using System...
在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
,我们可以在其中处理异常,例如设置一个标志位以通知其他代码线程已被中断。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c# wait 怎样处理中断异常
本文地址: https://pptw.com/jishu/709399.html