dotnet-state-machine / stateless

A simple library for creating state machines in C# code
Other
5.53k stars 765 forks source link

Fixed a null reference exception issue in InternalFireQueuedAsync method and added a fix to support multi-tasks firing triggers #535

Open YaeliGimelshtein opened 1 year ago

YaeliGimelshtein commented 1 year ago

Using this NuGet in my own app, I came across a null reference exception in InternalFireQueuedAsync method. After a bit of investigation I came to a conclusion that there are 2 things needed to be fixed: 1) there is a use of object Queue when it's better to use ConcurrentQueue in order to be thread safe and avoid exceptions. 2) there was no lock in the InternalFireQueuedAsync method so , what could happen (and happened in my own app) is that two threads will be able to go at the same time into the Dequeue sections and one of them will get null (if for example the queue has only one element).

I created 3 fixes: 1) changed the Queue object to ConcurrentQueue to support multiple threads 2) fixed the logic in the InternalFireQueuedAsync to support double-checked locking in order to make sure that threads will not be able to dequeue at the same time. 3) created a new test to test this functionality

for any more questions please feel free to contact me: yaeli.gimelshtein@kornit.com

vlm--- commented 1 year ago

Stateless is not designed to be thread safe as is noted in https://github.com/dotnet-state-machine/stateless/blob/dev/README.md#async-triggers. You can find some closed issues proposing similar fixes, but its easier for the user to ensure that the state machine is not used concurrently.

crozone commented 1 year ago

Thanks for the PR, but we need to have a design discussion surrounding the design of a threadsafe mode for Stateless since the current queue modes aren't intended to be threadsafe at all.

Please see https://github.com/dotnet-state-machine/stateless/issues/527 for discussion surrounding adding FiringMode.Serial for concurrent event firing. We are considering a SemaphoreSlim as the queuing mechanism since it will also support the async usecases.

YaeliGimelshtein commented 1 year ago

Thanks for your fast response. That's really weird since we have been using stateless for almost 2 years and for most of the time we never ran into a problem regarding parallelism or threads issues. Hoping you consider this since most apps today use concurrency. thanks :)

YaeliGimelshtein commented 1 year ago

Also, as in the mentioned PR, I also suggest the use of SemaphoreSlim but in a bit different way, since there is no need to add a new mode (queued will work perfectly with my change in order to support concurrency)