Use .Net UdpClient in a multithreaded environment

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

It looks something like this:

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:

I know UdpClient is not thread safe (according to MSDN documentation), what's the best way to support multithreading without using a blocking mechanism?

  • On every submission, create a new UdpClient instance? (just use your local UdpClient var). performance?

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

  • Any other solution?

+3


source to share


2 answers


In the end, I believe my current implementation should work without any problems (until Microsoft changes the implementation of the UdpClient class).



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

+1


source


I think the best way here is to create a new UdpClient

one every time the method is called. This way you can be sure that the code is safe. Performance is unlikely to be an issue, and if profiling shows it to be, only then should you start addressing it.



Also, you shouldn't forget to call EndSend()

after each one BeginSend()

(ideally in a callback).

0


source







All Articles