C# 无法将 lambda 表达式转换为类型“System.Delegate”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9549358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:50:58  来源:igfitidea点击:

Cannot convert lambda expression to type 'System.Delegate'

c#multithreadingdispatcher

提问by mpen

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:

我想要做的就是在我的主 UI 线程上调用一个内联方法。所以我在主线程上调用了这个:

_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 nota WPF application; I've referenced WindowsBaseso I could get access to the Dispatcherclass.

请注意,这不是WPF 应用程序;我已经引用了,WindowsBase所以我可以访问这个Dispatcher类。

采纳答案by thecoop

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

问题是您没有提供要调用的委托的确切类型Dispatcher.Invoke只需要一个Delegate. 它是Action<T>? 如果是,那是T什么?是MethodInvoker吗?Action? 什么?

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

如果您的委托不接受任何参数并且不返回任何内容,您可以使用ActionMethodInvoker。尝试这个:

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

回答by IAbstract

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.

除非我遗漏了什么,您告诉我们的只是这不是 WPF 应用程序。我认为 Dispatcher 不是正确使用的类。

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

如果这是一个 WinForm 应用程序,则可以通过WindowsFormsSynchronizationContext访问您的 UI 线程

回答by Narottam Goyal

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