由于您使用的是 .NET 2.0,因此您无法使用Func
委托,但您可以使用MethodInvoker委托。
您将无法在 .NET 2.0 中使用 lambda 表达式语法,但您可以使用“匿名委托”语法(这几乎是相同的东西),如下面的代码示例所示。
从非 UI 线程查询 UI 控件中的数据通常是不常见的事情;通常,您的 UI 控件会触发在 UI 线程上执行的事件,因此您当时从 UI 控件中收集所需的数据,然后将该数据传递给其他函数,因此您无需担心执行 Invoke .
但是,在您的情况下,您应该能够执行以下操作:
public ApplicationViewModel SelectedApplication
{
get
{
if (this.InvokeRequired)
{
ApplicationViewModel value = null; // compiler requires that we initialize this variable
// the call to Invoke will block until the anonymous delegate has finished executing.
this.Invoke((MethodInvoker)delegate
{
// anonymous delegate executing on UI thread due calling the Invoke method
// assign the result to the value variable so that we can return it.
value = _applicationsCombobox.SelectedItem as ApplicationViewModel;
});
return value;
}
else
{
return _applicationsCombobox.SelectedItem as ApplicationViewModel;
}
}
}
编辑:现在我查看了您的 .NET 4.0 代码示例并查看了 Invoke 函数,我看到了它如何返回一个值(不是我以前有理由使用的东西)。
好吧, MethodInvoker 委托不期望返回值,但正如@haiyyu 指出的那样,您可以定义自己的委托。例如,您只需要定义自己的Func<TResult>
委托,原始代码可能就可以正常工作:
// this is all that is required to declare your own Func<TResult> delegate.
delegate TResult Func<TResult>();
来自 MSDN 页面的示例代码:
public partial class Form1 : Form
{
public Form1()
{
// Create a timer that will call the ShowTime method every second.
var timer = new System.Threading.Timer(ShowTime, null, 0, 1000);
}
private void ShowTime(object x)
{
// Don't do anything if the form's handle hasn't been created
// or the form has been disposed.
if (!this.IsHandleCreated && !this.IsDisposed) return;
// Invoke an anonymous method on the thread of the form.
this.Invoke((MethodInvoker) delegate
{
// Show the current time in the form's title bar.
this.Text = DateTime.Now.ToLongTimeString();
});
}
}