Should a UdpClient be disposed of?
Asked Answered
P

1

5

When trying to dispose of a UdpClient, I found that it's impossible. For the following:

UdpClient udpClient = new UdpClient();
udpClient.Dispose();

Visual Studio shows an error:

'System.Net.Sockets.UdpClient.Dispose(bool)' is inaccessible due to its protection level

Does this mean that I should inherit from UdpClient and expose the Dispose (Since it seems to be the consensus that whatever implements IDisposable should be disposed of)? Is there some reason we shouldn't use the class directly? Or is there simply nothing to dispose of after calling Close?

Though a using statement does work - it's not suitable when listening.

Pacific answered 19/6, 2014 at 16:59 Comment(2)
If you were supposed to inherit from it, the constructors would be protected too, but they're public. The documentation is definitely misleading.Percept
protected virtual void UdpClient.Dispose(Boolean) has been around since .NET framework 2.0 whereas the parameter-less overload public void Dispose() is only available since 4.6. Your project is targeting framework < 4.6 so you only see the protected methodMeaghanmeagher
T
9

No you shouldn't. you should call UdpClient.Close ...


After looking at the source here: http://referencesource.microsoft.com/#System/net/System/Net/Sockets/UDPClient.cs#7682e0ea2c48b5cb

It appears you can either call Close or ((IDisposable)updClient).Dispose but API-wise I think calling Close is the way UDP client is intended to be used...

All this makes very little sense to me....

Turpitude answered 19/6, 2014 at 17:23 Comment(6)
Since it seems to be the consensus that whatever implements IDisposable should be disposed of - Do you have a source?Pacific
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. msdn.microsoft.com/en-us/library/bb360027.aspxTurpitude
@Pacific it's basically a design flaw from .Net 1.1Turpitude
+1 Thanks. That's a pretty clear source! Although, I'll admit I now don't understand this whole UdpClient.IDisposable.Dispose thing, and why doesn't the documentation for UdpClient.Dispose mention that. Perhaps there are two separate Dispose methods here... Anyway - thanks for the answer.Pacific
@Pacific looking at the source I don't get it. 'UdpClient.Close' is identical to 'UdpClient.IDisposable.Dispose'Turpitude
I think the UdpClient.IDisposable.Dispose API doc is for an Explicit Interface Implementation back in .NET 4.5.2. I don't see that API in the reference source, which is for 4.8, so I guess they got rid of it (?). I think that explains the confusion, at least for me.Otranto

© 2022 - 2024 — McMap. All rights reserved.