C# IAsyncResult到字节[]的转换

C# IAsyncResult到字节[]的转换,c#,asynchronous,.net-core,C#,Asynchronous,.net Core,下面我创建了一个类似的代码: public struct UDPState { public UdpClient UDPClient; public IPEndPoint RemoteIpEndPoint; } public static void receiveCallback(IAsyncResult ar) { UdpClient u = ((UDPState)(ar.AsyncState)).UDPC

下面我创建了一个类似的代码:

    public struct UDPState
    {
        public UdpClient UDPClient;
        public IPEndPoint RemoteIpEndPoint;
    }
    public static void receiveCallback(IAsyncResult ar)
    {
        UdpClient u = ((UDPState)(ar.AsyncState)).UDPClient;
        IPEndPoint e = ((UDPState)(ar.AsyncState)).RemoteIpEndPoint;

        byte[] receiveBytes = u.EndReceive(ar, ref e);
    }
    public Byte[] UDPSMClientReceive(UdpClient client, IPEndPoint ip)
    {
        try
        {
            UDPState state = new UDPState();
            state.UDPClient = client;
            state.RemoteIpEndPoint = ip;
            while (true)
            {
                Thread.Sleep(Convert.ToInt32(refreshTime));

                IAsyncResult receivedBytes = UDPClient.BeginReceive(new AsyncCallback(receiveCallback), state);

                return receivedBytes;
            }
        }
        catch (Exception e)
        {
            throw new Exception("ERROR!! Se han generado errores en la configuración UDP o en la recepción de paquetes: " + e);
        }
    }

我需要返回一个Byte[]而不是IAsyncResult,我已经四处查看了,但找不到任何关于它的文档。有没有办法完成这个任务,或者我遗漏了什么?

IAsyncResult不是结果,它代表异步调用。Begin/End方法在2010年引入任务之前使用的中使用。到目前为止,尤其是在.NETCore中,几乎所有类都使用任务

您可以使用。通过这种方式,您可以将方法简化为:

public async Task<Byte[]> UDPSMClientReceive(UdpClient client)
{
    try
    {
        var sleep=Convert.ToInt32(refreshTime);
        state.RemoteIpEndPoint = ip;
        while (true)
        {
            await Task.Delay(sleep);
            var result=await UdpClient.ReceiveAsync();
            return result.Buffer;
        }
    }
    catch (Exception e)
    {
        throw new Exception(e,"ERROR!! Se han generado errores en la configuración UDP o en la recepción de paquetes: " + e.Message);
    }
}
公共异步任务UDPSMClientReceive(UdpClient客户端)
{
尝试
{
var sleep=Convert.ToInt32(刷新时间);
state.RemoteIpEndPoint=ip;
while(true)
{
等待任务。延迟(睡眠);
var result=await UdpClient.ReceiveAsync();
返回结果缓冲区;
}
}
捕获(例外e)
{
抛出新异常(e,“ERROR!!Se han generado errors en la configuración UDP o en la recepción de paquetes:“+e.Message”);
}
}
我更改了异常处理程序,将原始异常作为内部异常包含在内。之后,不需要在消息中包含整个原始异常


异步IO操作不使用线程。一旦它们完成,执行将在线程池线程上继续,因此应避免
线程。睡眠

IAsyncResult
不是结果,它表示异步调用。不要使用古老的
Begin/End
方法,使用异步方法,如。这样,您可以只编写
var result=wait client.ReceiveAsync();var bytes=result.Buffer