I have number of event notifications happening each time for example a file is added to a folder (this is not my case but just an analogy to explain).
There could be any number of files added to folder, we dont know how many will there be.
Currently, my event myEvent_Handler fires each time a file is added
private void myEvent_Handler(object sender, SomeEvent e)
{
// I dont know how many times this event will fire
if (something == true) (1)
{
var t = Task.Run(() =>
{
DoSomething(e); (2)
});
}
}
The problem in above event handler is the race condition btw line marked with (1) and (2). For example, the event is fired 4 times:
- (1) is true, (2) is queued in a task to run
- (1) is true, (2) is queued in a task to run
- (1) is true, (2) is queued in a task to run
- (1) is true, (2) is queued in a task to run
Now, tasks queue has 4 tasks to run but these are not executed in same order. They could execute in any order, i.e. 3->2->4->1 but I need them to execute as 1->2->3->4 without blocking UI thread.
How can I achieve this without blocking UI thread?