由于您使用.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的代码示例,也看调用函数,我看它如何返回一个值(不是我以前有理由使用的东西)。
那么,MethodInvoker委托并不期望返回值,但@haiyyu指出,您可以定义自己的委托。举例来说,你只需要定义自己的Func<TResult>
委托,和原来的代码可能会很好地工作:从MSDN页面
// this is all that is required to declare your own Func<TResult> delegate.
delegate TResult Func<TResult>();
示例代码:
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();
});
}
}
你可以创建自己的委托。 – haiyyu 2012-02-22 14:40:02