如何使用异步在一个循环收获UdpClient? [英] How to use asynchronous Receive for UdpClient in a loop?

查看:113
本文介绍了如何使用异步在一个循环收获UdpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个多线程应用程序。一个线程负责处理该来自外部的硬件UDP消息。我目前使用在一个循环中UdpClient.Receive方法。我相信,Receive方法阻塞的线程在等待下一条消息。我有一个共享变量(_isCancelled)如果我想关闭所有的线程和缓慢停止运行的应用程序,我使用。但是,由于这种Receive方法阻止我不能正常关闭应用程序,如果通信已失去了外部的硬件。这是当前code环

I am building a multi-threaded application. One of the threads is responsible for processing UDP messages that come from an external piece of hardware. I am currently using the UdpClient.Receive method in a loop. I believe that the Receive method blocks the thread while waiting for the next message. I have a shared variable (_isCancelled) that I use if I want to shut down all of the threads and gracefully stop the application. However because this Receive method blocks I can't gracefully shut down the application if communication has been lost to the external piece of hardware. Here is the current code loop

UdpClient _client = new UdpClient(8000);
IPEndPoint _endPoint = new IPEndPoint(IPAddress.Any, 8000);
while (!_isCancelled)
{
  byte[] _bytes = _client.Receive(ref _endPoint);
  ...process data...
}

我在想,我应该使用异步接收方法。但我不能完全确定我了解那些工作,我应该怎么构建我的code。我想能够continuouslly接收数据并对其进行处理。在任何时候,我希望能够通过设置_isCancelled为true,以正常关闭线程。如果因为某些原因,我们失去了通信与外部硬件或没有收到任何消息,我们应该仍然能够正常关闭线程。

I am thinking that I should instead use the asynchronous Receive methods. But I am not completely sure I understand how those work and how I should structure my code. I want to be able to continuouslly receive data and process it. And at any time I want to be able to gracefully shut down the thread by setting _isCancelled to true. And if for some reason we lose communication to the external hardware or don't receive any more messages, we should still be able to gracefully shut down the thread.

推荐答案

有关使用新的方法,而不是TAP的开始/结束的方法,你可以使用.NET 4.5以下

For newer methods using TAP instead of Begin/End method you can use the following in .Net 4.5

这很简单!

    private static void UDPListener()
    {
        Task.Run(async () =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var receivedResults = await udpClient.ReceiveAsync();
                    loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
                }
            }
        });
    }

同步方法

至于放在附近上述异步的方法,这也可以在同步方法来实现在一个非常相似的时装

Synchronous Method

As appose to the asynchronous method above, this can be also implemented in synchronous method in a very similar fashion:

    private static void UDPListener()
    {
        Task.Run(() =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    var receivedResults = udpClient.Receive(ref remoteEndPoint);
                    loggingEvent += Encoding.ASCII.GetString(receivedResults);
                }
            }
        });
    }

这篇关于如何使用异步在一个循环收获UdpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆