Occasionally, my current application freezes. With Visual Studio attached, I pause debugging and observe the current threads and their call stack. I find two or more Threads that wait for another. I am not sure if it is a real deadlock, for the last thread in the chain does not state "warting for lock.." but "..WaitHandle.WaitOneNoCheck".
I managed to create a minimal sample that demonstrates the situation. The freeze seems to appear when the subscribed onNext-action has not completed yet, but the throttled stream already serves a new event.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown") // Not using a UI-stream fixes the problem. e.g. Observable.Interval(TimeSpan)
//.ObserveOn(Scheduler.Default) // Adding this line fixes the problem
.Throttle(TimeSpan.FromMilliseconds(100)) // No use of throttle fixes the problem
.Subscribe(_ =>
{
for (int i = 0; i < 5; i++)
{
Application.Current.Dispatcher.Invoke(() => Thread.Sleep(200)); // No usage of Dispatcher fixes the problem
}
});
}
These are the involved threads. Reproduce the error in a plain simple WPF window and hitting some keys.
As per the comments in demo-code, I found serveral ways to avoid these kind of freezes. I just wonder if there is an explanation why the freeze happens. Or is it a bug in System.Reactive
or even the Dispatcher
?
I observe this in net472, net5 and net6.