, 당신은 당신에게 Func
위임을 사용할 필요가 없습니다,하지만 당신은 MethodInvoker 대리자를 사용할 수 있습니다 여기에 좀 더 읽기입니다.
.NET 2.0에서는 람다 식 구문을 사용할 수 없지만 아래 코드 예제와 같이 "익명 대리자"구문을 사용할 수 있습니다.
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