0

I have this 3rd party library that exposes a Connect method, which is not time-bound in any way shape or form. If it fails it raises an exception after many many minutes. Peeking in looks like it's using TcpClient to make the calls.

What's the elegant way to time-bound a call to 3rdPartyLibObject.Connect() in my code?

Of course, I can always just Task.Run() my way into it —

var task = Task.Run(() =>
{
    return IHopeYouReNotInAHurryMethod();
});

bool completed = task.Wait(5000);

but that seems to be frowned upon for anything but CPU pegging work, and this is definitely not it.

evilSnobu
  • 24,582
  • 8
  • 41
  • 71
  • Possible duplicate of [How to async this long running method?](https://stackoverflow.com/questions/32617702/how-to-async-this-long-running-method) – maccettura Jul 12 '18 at 15:20
  • My guess is it is the same as any socket connection in Windows (assuming this is your OS). My undersatnding is that the closing of the socket cannot be guaranteed by the runtime and is managed by Windows so if you fire and forget you can be left there for a while or the socket will close in the background at some point. My suggestion is to do exactly what you call 'frowned-upon' and manage your timeout yourself, therefore you are explicitly handling an 'undesired' outcome. – Michael Coxon Jul 12 '18 at 15:32
  • Can i override `TcpClient` for the whole app domain, thus affecting the behaviour of that library as well? – evilSnobu Jul 12 '18 at 15:44
  • I don't think so - and I think it would be bad to do that. Windows has a default 240 second timeout for connections to make sure there is no missed incoming data. My guess is that the third-party library is not implemented correctly and is giving you troubles. The best bet would be to handle timeouts yourself and then log a bug with the third-party devs to fix the issue. I know that, that is not as simple as it sounds but your only other option is 'peeking' at the library and re-implementing the part that is done poorly. (source: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) – Michael Coxon Jul 12 '18 at 15:51

0 Answers0