Cannot convert lambda expression to type 'System.Delegate'

C#MultithreadingDispatcher

C# Problem Overview


Neither of these work:

_uiDispatcher.Invoke(() => { });
_uiDispatcher.Invoke(delegate() { });

All I want to do is Invoke an inline method on my main UI thread. So I called this on the main thread:

_uiDispatcher = Dispatcher.CurrentDispatcher;

And now I want to execute some code on that thread from another thread. How do I do it? Am I using the wrong syntax?

Note that this is not a WPF application; I've referenced WindowsBase so I could get access to the Dispatcher class.

C# Solutions


Solution 1 - C#

The problem is that you aren't providing the exact type of delegate you want to invoke. Dispatcher.Invoke just takes a Delegate. Is it an Action<T>? If so, what is T? Is it a MethodInvoker? Action? What?

If your delegate takes no arguments and returns nothing, you can use Action or MethodInvoker. Try this:

_uiDispatcher.Invoke(new Action(() => { }));

Solution 2 - C#

 this.Dispatcher.Invoke((Action)(() => { textBox1.Text = "Test 123"; }));

Solution 3 - C#

Expanding on other answers a little.

Action with no parameters:

_uiDispatcher.Invoke(new Action(() =>
{
    // Do stuff
    textBox1.Text = "Test 123";
}));

Action with 1 parameter:

_uiDispatcher.Invoke(new Action<bool>((flag) =>
{
    if (flag)
    {
        // Do stuff
        textBox1.Text = "Test 123";
    }

}));

Action with 2 parameters:

_uiDispatcher.Invoke(new Action<int, string>((id, value) =>
{
    // Do stuff
    textBox1.Text = $"{value} {id}";
}));

And so on...

Solution 4 - C#

Unless I've missed something, all you've told us is this is not a WPF application. I don't think the Dispatcher is the correct class to use.

If this is a WinForm app, your UI thread can be accessed via the WindowsFormsSynchronizationContext

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - C#thecoopView Answer on Stackoverflow
Solution 2 - C#Narottam GoyalView Answer on Stackoverflow
Solution 3 - C#JohnBView Answer on Stackoverflow
Solution 4 - C#IAbstractView Answer on Stackoverflow