c# 调用接口,避免接口内部卡死,实现超时退出 3.0
【代码】c# 调用接口,避免接口内部卡死,实现超时退出。
·
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("连接超时");
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)