正确使用调用

nan*_*ana 1 c# invoke backgroundworker winforms

我有一个关于 invoke 用法的一般问题。我的大多数 C# winforms 项目都有一个后台工作人员和一个 UI。很快我意识到我需要来自后台工作人员 UI 的信息,或者我需要更改我的后台工作人员的 UI。例子:

//example invoke usage to get information from UI (dateMatch = CheckBox, fromDate&toDate = Datepicker)
bool isDateMatch = false;
dateMatch.Invoke(new MethodInvoker(delegate { isDateMatch = dateMatch.Checked; }));
DateTime fromDt = new DateTime();
fromDate.Invoke(new MethodInvoker(delegate { fromDt = fromDate.Value; }));
DateTime toDt = new DateTime();
toDate.Invoke(new MethodInvoker(delegate { toDt = toDate.Value; }));
Run Code Online (Sandbox Code Playgroud)
//example invoke usage to change UI (statusTxt = TextBox, progressBar = ProgressBar)
private void changeStatus(string statusTextV, bool enableProgressBar)
{
   statusTxt.Invoke(new MethodInvoker(delegate { statusTxt.Text = statusTextV; }));
   progressBar.Invoke(new MethodInvoker(delegate { progressBar.MarqueeAnimationSpeed = enableProgressBar ? 1 : 0; }));
}
Run Code Online (Sandbox Code Playgroud)

我的意思是我的代码充满了调用方法。这是坏事吗,有没有更好的方法来做到这一点。

Mar*_*ell 6

所有控件都将位于同一个UI 线程上——与表单本身相同,因此无需进行多次调用——并且您可以使用更简单的语法:

private void changeStatus(string statusTextV, bool enableProgressBar)
{
   调用((MethodInvoker)委托{
        statusTxt.Text = statusTextV;
        progressBar.MarqueeAnimationSpeed = enableProgressBar ?1:0;
    });
}