停止从udpclient ReceiveAsync接收

时间:2014-10-02 23:47:42

标签: c# task-parallel-library udpclient tpl-dataflow

我正在提取要从数据库接收的端口列表。我正在接受这些端口并创建UdpClients列表。

public static ConcurrentBag<UdpClient> Clients { get; set; }

然后,我选择任何有可用数据的通道,并将UdpRecieveResult发送到TPL数据流缓冲区块。

 var readyChannels =
                (from channel in Clients
                 where (channel.Available > 0)
                 select channel);

 foreach (var channel in readyChannels)
                    {
                        // await on the result of the task                            
                        var t = Task.Factory.StartNew(() => ReceiveAndRespond(channel));                            
                    }   


  async Task ReceiveAndRespond(UdpClient channel)
    {
        UdpReceiveResult? result = null;

        try
        {                
                result = await channel.ReceiveAsync();                
        }
        catch(Exception exc)
        {
            logger.Error("Error receiving from channel: " + exc.Message, exc);
        }

        if (result != null)
        {
                UdpData data = new UdpData() { Data = result.Value.Buffer, LocalPort = ((IPEndPoint)channel.Client.LocalEndPoint).Port, LocalIP = ((IPEndPoint)channel.Client.LocalEndPoint).Address, RemoteEndpoint = result.Value.RemoteEndPoint };
                await Flow.bufferBlock.SendAsync(data);
                logger.Info("Packet received from {0}", data.LocalPort);                                 
        }
    }

例外:

Error receiving from channel: Cannot access a disposed object.Object name: 'System.Net.Sockets.UdpClient'.

如何停止接收ReceiveAsync?所以给定Udpclients监听列表,如果我想停止接收特定的UdpClient,怎么能实现呢?

0 个答案:

没有答案