dotnet / dotnet/wpf

Dispatcher.Invoke() blocks Parallel.For execution on .NET 7

Open
#8,066 7 comments 0 reactions 0 assignees View on GitHub
Investigate Priority:3
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

### Description

When an Invoke() is called to update a UI object in the handler of a Threading.Timer, the execution of a simple Parallel.For gets stuck.

I report here this [issue ](https://github.com/dotnet/runtime/issues/73001) previously opened in dotnet/runtime because they said it's not a problem with the Paralle.For
I know I should avoid running a Parallel.For on the UI thread, but I think the execution should not hang.

### Reproduction Steps

Here is a small WPF sample to reproduce the issue:

```



```

```
public partial class MainWindow : Window
{
private System.Threading.Timer timer;
private int count = 0;

public MainWindow()
{
InitializeComponent();
}

protected override void OnContentRendered(EventArgs e)
{
timer = new Timer(TimerHandler, null, 0, 20);

for (int i = 0; i < 100; i++)
{
Stopwatch sw = Stopwatch.StartNew();

Parallel.For(0, 10, i =>
{
Thread.Sleep(1); // do some stuff
});

sw.Stop();
Debug.WriteLine("elapsed time: " + sw.ElapsedMilliseconds);
}

base.OnContentRendered(e);
}

public void TimerHandler(Object stateInfo)
{
count++;

Dispatcher.Invoke(() =>
{
Label1.Content = count;
});
}
}
```

### Expected behavior

Parallel.For doesn't hang or slow down

### Actual behavior

Parallel.For hangs

### Regression?

The same application on .NET Framework doesn't produce so bad performance, the Parallel.For take about 150ms
On .NET 6 the Parallel.For take about 2 seconds but it doesn't stuck.

### Known Workarounds

_No response_

### Impact

_No response_

### Configuration

.NET 7
Windows 11 version 21H2

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.