I just got notice about using "Using", as it´s very efficient in it´s way to handle disposable objects. As it will only use them in that certain command, then it will be removed.
But i don´t know where the limit goes, as i can´t see that you Always want´s to use it, and It´s Always efficient.
So my question here is. Is this a good way to use it, or is it unnecessary or will it even hurt my performance in any way?
void Sending(object sender, NAudio.Wave.WaveInEventArgs e)
{
using (UdpClient udpclient = new UdpClient())
{
if (connect == true && MuteMic.Checked == false)
{
udpclient.Send(e.Buffer, e.BytesRecorded, otherPartyIP.Address.ToString(), 1500);
}
}
}
It´s an event from NAudio, and what it does is, While WaveInEvent has any data, do this.
WaveInEvent is from an input device, so if i start recording with it (example mic), data will be available (the mic audio), and then i can do what i want with that data. In this case i am sending it over UDP.
But as you can see, i am using a local udpclient. I don´t know if i should be using it there, or if i should have one created before so it can reuse it all the time, instead of making a new.
Hope i didn´t mess up my explanation to bad.
Is this a good way to use it, or is it unnecessary or will it even hurt my performance in any way?
You should always use it when any object implementes IDisposable. It doesn't have any negative impact on performance. All it will do is to ensure that object is properly disposed.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. Your code will more or less look like this for the compliler.
{
UdpClient udpclient = new UdpClient();
try
{
if (connect == true && MuteMic.Checked == false)
{
udpclient.Send(e.Buffer, e.BytesRecorded, otherPartyIP.Address.ToString(), 1500);
}
}
finally
{
if (udpclient!= null)
((IDisposable)udpclient).Dispose();
}
}
You can read the details of using here.