C# SendAysnc 超时
业务方法
public override async task<list<(ipendpoint endpoint, byte[] data)>> sendasync(ipendpoint server, byte[] data2, int getresponsecount = 1)
{
//随机使用端口,支持并发
using (udpclient udpclient = new udpclient(localipendpoint)) //广播包在有虚拟机的时候必须指定有效网卡
{ //多网卡容易丢包
udpclient.client.sendtimeout = sendtimeout;
udpclient.client.receivetimeout = receivetimeout;
byte[] data = isencrypt ? encrypt(data2) : data2;
try
{
int sendlength = await udpclient.sendasync(data, data.length, server);
//int sendlength = 0;
//udpclient.sendasync(data, data.length, server).wait(sendtimeout); //同步方法
log?.invoke($"send:{server.tostring()},len:{sendlength}/{data.length},data:{new q.mina.iobuffer(data).gethexdump()}");
udpclient.close();
return result;
}
catch (exception ex)
{
return null;
}
}
}
@@#
对上述方法调用,可以使用三种方式
异步,业务方法正常执行,超时处理正常,推荐使用此方法
var result = await new q.sockets.udphelper2() { localipendpoint = localip, receivetimeout = 1000 }.sendasync(ip, data, 1000);
@@#
同步,超时未生效,一直处于等待状态,除非方法内使用udpclient.sendasync(data, data.length, server).wait(sendtimeout); //同步方法
new q.sockets.udphelper2() { localipendpoint = localip, receivetimeout=1000 }.sendasync(ip, data, 1000).result
@@#
等待指定时间,强行在外部指定超时,打断了业务方法的执行时间(如接收大量数据)
var x = new q.sockets.udphelper2() { localipendpoint = localip, receivetimeout = 1000 }.sendasync(ip, data, 1000);
x.wait(3000);
if (x.iscompleted)
{
show(x.result);
}
@@#