C#多线程异常处理

C#的子线程的异常处理,直接上代码吧。
首先是Thread,下面这种情况程序会直接抛异常

        static void Main(string[] args)
        {
            try
            {
                Thread th = new Thread(Th);
                th.Start();
            }
            catch (Exception ex)
            {
                //此处永远不会被执行
                Console.WriteLine("get ex in child thread");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        static void Th()
        {
            string s = null;
            int a = s.Length;
        }

下面在子线程中添加异常捕捉:

        static void Main(string[] args)
        {
            try
            {
                Thread th = new Thread(Th);
                th.Start();
            }
            catch (Exception ex)
            {
                //此处永远不会被执行
                Console.WriteLine("get ex in child thread");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

        static void Th()
        {
            try
            {
                string s = null;
                int a = s.Length;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

执行结果:
在这里插入图片描述
综上所述,使用Thread时,子线程的异常需要在子线程的内部自行处理,主线程无法捕获子线程的异常。

下面来看看使用Task的情况

        static void Main(string[] args)
        {
            try
            {
                Task t = Task.Run(() =>
                  {
                      string s = null;
                      int a = s.Length;
                  });

                t.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("get ex in child thread");
                Console.WriteLine($"the type of Exception is: {ex.GetType().Name}");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

运行结果:
在这里插入图片描述
下面用异步函数的方式:

        static async Task Main(string[] args)
        {
            try
            {
                await Task.Run( async () =>
                {
                    string s = null;
                    int a = s.Length;
                    await Task.Delay(100);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("get ex in child thread");
                Console.WriteLine($"the type of Exception is: {ex.GetType().Name}");
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }

看看运行结果:
在这里插入图片描述
由此可见使用Task和异步函数,可以对异常更加方便的处理,若使用Thread类创建的线程,则需要在子线程代码中处理异常。
对异常进行合适的处理对于程序的健壮性有很大的好处,更重要的是当出现问题的时候可以快速定位到问题。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用C#线程ping并将结果写入文件的示例代码: ```csharp using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Threading; class Program { static void Main(string[] args) { // 创建一个列表,包含要ping的IP地址 List<string> addresses = new List<string> { "www.google.com", "www.baidu.com", "www.microsoft.com", "www.apple.com", "www.amazon.com" }; // 创建一个文件流,用于写入ping结果 using (StreamWriter writer = new StreamWriter("ping_results.txt")) { // 创建一个计数器,用于跟踪已完成ping的地址数量 int count = 0; // 遍历IP地址列表 foreach (string address in addresses) { // 创建一个新线程执行ping操作 Thread t = new Thread(() => { try { // 创建一个Ping对象并发送ping请求 Ping pingSender = new Ping(); PingReply reply = pingSender.Send(address); // 将ping结果写入文件 writer.WriteLine("{0}: {1}", address, reply.Status); } catch (Exception ex) { // 发生异常时也将结果写入文件 writer.WriteLine("{0}: {1}", address, ex.Message); } finally { // 计数器加1 Interlocked.Increment(ref count); } }); // 启动线程 t.Start(); } // 等待所有线程完成 while (count < addresses.Count) { Thread.Sleep(100); } } Console.WriteLine("Ping完成,结果已写入文件。"); Console.ReadKey(); } } ``` 在此示例中,我们使用了一个`List<string>`对象来存储要ping的IP地址。我们遍历该列表,并为每个地址创建一个新线程执行ping操作。每次ping完成后,我们将结果写入一个文件中。 注意,我们在写入文件时使用了`StreamWriter`类,它会自动处理文件流的打开和关闭。我们还使用了`Interlocked.Increment`方法来对计数器进行原子操作,以确保线程安全。最后,我们在主线程中等待所有线程完成后输出一个完成消息。 当然,这只是一个简单的示例,你可以根据自己的需求对代码进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值