在多线程环境中使用.Net UdpClient [英] use .Net UdpClient in a multithreaded environment

查看:154
本文介绍了在多线程环境中使用.Net UdpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个为某些线程服务的类的实例(我们称其为A),该实例仅通过UdpClient类发送UDP数据包。
会在其构造函数中初始化UdpClient,仅用于发送数据包。

I have an instance of a class (lets call it A) which serves some threads, this instance only sends UDP packets via the UdpClient class. It initialize the the UdpClient in its constructor and only serves to send the packets.

它看起来像:

public class A{

private UdpClient m_Client;
public class A(string host, int port){

    m_Client = new UdpClient(host, port);
}

public void Send(string dataToSend){

 var data= encoding.GetBytes(dataToSend);
 client.BeginSend(data, data.Length, null, null);
}

}

我的问题是:

我知道UdpClient不是线程安全的(根据MSDN文档),在不使用锁定机制的情况下支持多线程的最佳方法是什么?

I know that UdpClient isn't thread-safe (according to MSDN documentation), what is the best way to support multithreaded without using locking mechanism?


  1. 在每次发送时都创建UdpClient的新实例吗? (只需使用一些本地UdpClient变量)。
    性能?

  1. On each send create new instance of the UdpClient? (just use some local UdpClient var). performance?

使用ThreadLocal作为UdpClient吗?但是在这种情况下如何处置UdpClient?

Use ThreadLocal for the UdpClient? but what about the disposing of the UdpClient in this situation?

还有其他解决方案吗?


推荐答案

最终,我相信我当前的实现应该没有问题(只要Microsoft不会更改UdpClient类的实现)。

Eventually I believe that my current implementation should work with no issues (as long as Microsoft won't change the UdpClient class implementation).

对于谁可能很有趣:
http://social.msdn.microsoft.com/Forums/zh-CN/csharpgeneral/thread/cbdd9818-00f0-499f-a935-d8e555899d64

这篇关于在多线程环境中使用.Net UdpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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