I am using Fleck (a C# websocket server) for a project I'm doing and I ran into a problem.
Generally, Fleck receives data from a web socket using this function:
public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset)
{
try
{
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s);
Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null);
task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
catch (Exception e)
{
error(e);
return null;
}
}
For each message the websocket receives, I run an async worker function that uses some CPU.
The problem is that for some reason, whenever I have multiple worker functions running, this Receive function receives inputs at a much slower rate than they are sent (via Chrome or Firefox).
I'm looking for a way to give it priority over the worker functions - meaning whenever a message is received, I want to run another function which will then queue up a new worker function.
The reason for that is that the websocket can be closed or receive a cancellation message, but the cancellation message isn't read until after almost all messages have been processed (tens of minutes later), which causes it to do close to nothing.
I have tried multiple different ways of queuing worker functions, including:
awaiting its resultAsyncQueue or ConcurrentQueueTaskFactory.StartNew with a variety of flags, both on the websocket runner function and the worker threadsThread and giving it a higher/lower priorityNone of these methods solved the problem.
I think I'm misunderstanding something basic about how the C# task scheduler works, but I just can't figure it out.