c# 调用接口,避免接口内部卡死,实现超时退出 3.0

using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        // 创建一个新的线程来调用接口
        Thread thread = new Thread(CallCInterface);
        thread.Start();

        // 等待一段时间,如果超时则中断线程
        bool timeout = !thread.Join(TimeSpan.FromSeconds(5)); // 设置超时时间为5秒
        if (timeout)
        {
            thread.Abort(); // 中断线程
            Console.WriteLine("C interface call timed out.");
        }
        else
        {
            Console.WriteLine("C interface call completed successfully.");
        }
        Console.ReadKey();
    }

    public static void CallCInterface()
    {
        int i = 0;

        while(true)
        {
            Console.WriteLine(i++);
            Thread.Sleep(1000);
        }
    }
}

虽然使用Thread类和Join方法设置连接超时时间,但是在连接超时时直接中止线程并抛出异常是不安全的,并且未正确处理连接超时的情况。建议使用异步方法和Task来处理连接超时

                 _client = new TcpClient();
                var connectTask = _client.ConnectAsync(_ip, _port);
                var timeout = Task.Delay(_connectTimeout);

                await Task.WhenAny(connectTask, timeout);

                if (!connectTask.IsCompleted)
                {
                    throw new TimeoutException("连接超时");
                }

添加一个CancellationToken参数,以便能够在需要时取消异步操作。

                    using (var cts = new CancellationTokenSource())
                    {
                        cts.CancelAfter(_connectTimeout);

                        var connectTask = _client.ConnectAsync(_ip, _port);
                        var timeout = Task.Delay(_connectTimeout, cts.Token);

                        await Task.WhenAny(connectTask, timeout);

                        if (!connectTask.IsCompleted)
                        {
                            throw new TimeoutException("连接超时");
                        }
                    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的ThreadID [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] public static extern Int32 GetCurrentWin32ThreadID(); #endregion #region 登记访问任务子线程 /// /// 访问任务子线程 /// public static Hashtable TaskThreadIDTable = Hashtable.Synchronized(new Hashtable()); private static int[] TaskThreadIDs { get { int[] IDs = new int[TaskThreadIDTable.Keys.Count]; TaskThreadIDTable.Keys.CopyTo(IDs, 0); return IDs; } } public static void RegisterThread(int _threadid, System.Threading.Thread thread) { if (!TaskThreadIDTable.ContainsKey(_threadid)) TaskThreadIDTable.Add(_threadid, thread); if (!ExitInvalidThreadLoopRunning) { Thread ExitInvalidThreadLoopThread = new Thread(new ThreadStart(ExitInvalidThreadLoop)); ExitInvalidThreadLoopThread.Priority = ThreadPriority.AboveNormal; ExitInvalidThreadLoopThread.Start(); } } #endregion #region 关闭,退出超时的用户线程 private static DateTime ExitInvalidThreadLoop_LastRunTime = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); private static bool ExitInvalidThreadLoopRunning { get { return DateTime.Now.Subtract(ExitInvalidThreadLoop_LastRunTime).TotalMinutes 10) { try { Thread thread = (Thread)TaskThreadIDTable[t.Id]; thread.Abort(); } catch { } t.Dispose(); } } #endregion } #endregion
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ou.cs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值