Background Threads & Cancellation Tokens

Start a thread in the background as a fire and forget, but have it check for cancellation in its internal notification loop.

ThreadPool use to queue up the delegate that starts the thread

threadSource = new CancellationTokenSource();
// Use thead pool to start a background thread
ThreadPool.QueueUserWorkItem(NotificationListener, threadSource.Token);

Details below

  • The listener starts the parameterized background thread
  • Background thread start with a try/catch system to crash gracefully if needed
  • Notification loop gets the passed down cancellation token to use for continuation checks
private void NotificationListener(object cancelToken)
{
	var threadParams = StartNotificationLoop((CancellationToken) cancelToken);
	var newThread = new Thread(threadParams)
	{
		IsBackground = true,
		Name = $"{this.GetType().Name}_{Guid.NewGuid()}"
	};
	newThread.Start(cancelToken);
}

private ParameterizedThreadStart StartNotificationLoop(CancellationToken token)
{
	var threadParams = new ParameterizedThreadStart(o =>
	{
		NotificationControl(token);
	});
	return threadParams;
}

private void NotificationControl(CancellationToken token)
{
	try
	{
		NotificationLoop(token);
	}
	catch (Exception e)
	{
		// ignored because why the fuck not
	}
	finally
	{
		Active = false;
		OnNotificationProcessStopped();
	}
}

private void NotificationLoop(CancellationToken token)
{
	while (!token.IsCancellationRequested)
	{
		var message = ReceiveEvent(); // This blocks until event received
		Active = true;
		if (!string.IsNullOrWhiteSpace(message))
		{
			OnTableChanged(message);
		}
	}
}