question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Stop() seems to be hanging

See original GitHub issue

Hi,

I have some trouble managing the channel close on client request. I’m in an ASP.Net Core / .NetCore 5 environment.

I wrote a wrapper as an injected service with Singleton scope around your library which you can find below. This service is called on background using Hangfire.

When I Ctrl+C the console server, I managed to tell the Hangfire job to call the stop method of my websocket service. Stop() fires the exit event, so that the second part of the Listen() method (where it stops) is executed. The end of the Listen() method is reached, but later on, Hangfire throws the exception when a job was not gracefully stopped. I think there is an issue with disposing the client, and / or subscriptions to events.

private WebsocketClient _client;
private ManualResetEvent _exitEvent;
public bool Connected;

public void Start()
{
	// Logging
	var identifier = $"[ {nameof(StandardSocketService)}.{nameof(Start)} ]";
	_logger.LogInformation($"{identifier} Starting connexion to WebSocket {_endpoint}");

	// Connect and listen
	_exitEvent = new ManualResetEvent(false);
	var url = new Uri(_endpoint);

	// callbacks
	_client = new WebsocketClient(url) { ReconnectTimeout = TimeSpan.FromMilliseconds(ReconnexionTimeout) };
	_client.DisconnectionHappened.Subscribe(info =>
	{
		Connected = false;
		_logger.LogInformation($"{identifier} Disconnection happened, type: {info.Type}");
	});
	_client.ReconnectionHappened.Subscribe(info =>
	{
		_logger.LogInformation($"{identifier} Reconnection happened, type: {info.Type}");
	});
	_client.MessageReceived.Subscribe(msg =>
	{
		_logger.LogInformation($"{identifier} Message received: {msg}");
	});
	// Actual start
	_client.Start();
	Connected = true;
	_logger.LogInformation($"{identifier} Started connexion to WebSocket {_endpoint}");
}

public void Listen()
{
	if (!Connected) Start();
	// Logging
	var identifier = $"[ {nameof(StandardSocketService)}.{nameof(Listen)} ]";
	_logger.LogInformation($"{identifier} Listening to WebSocket {_endpoint}");
	_exitEvent.WaitOne(); // block here until receive _exitEvent.Set();

	// We reach here when shutdown of application is required
	_client.IsReconnectionEnabled = false;
	_client.Stop(WebSocketCloseStatus.Empty, string.Empty);
	Connected = false;
	_logger.LogWarning($"{identifier} Closed connexion to WebSocket {_endpoint}");
}

public void Send(string data)
{
	if (!Connected) Listen();
	_client.Send(data);
}

public void Stop() => _exitEvent.Set();

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
kall2solliescommented, Feb 26, 2021

Works like a charm with the AsyncEx nuget package, and the pattern you provided! Thanks for your knowledge!

1reaction
kall2solliescommented, Feb 25, 2021

Thanks a lot for the tips, I’ll dig further about AsyncManualResetEvent. As a pure Web backend developer, dealing with threads is way out of my comfort zone ! And thanks for the Task.Factory.StartNew(), I remembered the Thread.Start() was almost deprecated, but couldn’t remember of the former. Anyway, since then, I gave up the Thread thing for a simple await exactly the same way you mentioned. I’ll just have to replace the infinite loop given your hints.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to stop HttpClient.GetAsync(uri) from hanging?
It should go to the response.EnsureSuccessStatusCode(); line, but it's not. It just seems to be hanging. c# · asp.net-web- ...
Read more >
How do I Stop the Terminal from Hanging When Using ...
After switching around a few of the lines, I can confirm that the terminal is not hanging on plt.show() anymore, but it is...
Read more >
Kill a Windows Service That Stucks on Stopping or Starting
The easiest way to stop a stuck service is to use the built-in taskkill command-line tool. First of all, you need to find...
Read more >
Add a timeout option, to prevent hanging #951
I'd like to propose adding a timeout option to the Fetch API. Prior issue: I know this was in #20, but that discussion...
Read more >
STOP FREEZING/HANGING UNITY!!!
Although my target is web player, having to switch platforms just to get the editor not to hang and random points seems odd...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found