2

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.

enter image description here

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.

sa.he
  • 1,391
  • 12
  • 25
  • I bet the source of trouble is that you intentionally block UI thread by callig Thread.Sleep on it. – emoacht Feb 04 '22 at 13:35
  • The sleep just makes the demonstration simple. My real code does not have sleeps, but other more or less complication calculations. Dispatching to the UI thread is done for adding/removing items from a ObservableCollection. – sa.he Feb 06 '22 at 19:26
  • In case you or any other readers haven't already seen this, [this chapter](http://introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html#SchedulingAndThreading) from Introduction to Rx is probably useful. – NickL Mar 01 '22 at 10:05
  • @NickL are you suggesting that this chapter explains the described situation? If so, I fail to find it. – sa.he Mar 06 '22 at 21:54

0 Answers0