use .Net UdpClient in a multithreaded environment

こ雲淡風輕ζ 提交于 2019-12-19 10:19:10

问题


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.

It looks something like:

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);
}

}

My questions is:

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. On each send create new instance of the UdpClient? (just use some local UdpClient var). performance?

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

  3. Any other solution?


回答1:


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

For whom it might be interesting: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/cbdd9818-00f0-499f-a935-d8e555899d64




回答2:


I think the best way here would be to create a new UdpClient every time the method is called. This way, you can be sure the code is safe. The performance isn't likely to be a problem, and if profiling shows that it is, only then you should start solving that.

Also, you shouldn't forget to call EndSend() after each BeginSend() (ideally in the callback).



来源:https://stackoverflow.com/questions/14868927/use-net-udpclient-in-a-multithreaded-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!