Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么使用Dispatcher.CurrentDispatcher.BeginInvoke不会更新我的GUI,但使用BeginInvoke会更新?_C#_Multithreading_Winforms_Dispatcher - Fatal编程技术网

C# 为什么使用Dispatcher.CurrentDispatcher.BeginInvoke不会更新我的GUI,但使用BeginInvoke会更新?

C# 为什么使用Dispatcher.CurrentDispatcher.BeginInvoke不会更新我的GUI,但使用BeginInvoke会更新?,c#,multithreading,winforms,dispatcher,C#,Multithreading,Winforms,Dispatcher,我对Dispatcher.CurrentDispatcher.BeginInvoke和BeginInvoke之间的区别感到困惑 我有以下部分代码不起作用,UpdateCounts方法中的代码被忽略: private void Start() { _testResults = new TestResults(ModelNameTextBox.Text); _timer = new System.Threading.Timer(UpdateCounts, null, 0, 500);

我对Dispatcher.CurrentDispatcher.BeginInvokeBeginInvoke之间的区别感到困惑

我有以下部分代码不起作用,UpdateCounts方法中的代码被忽略:

private void Start()
{
    _testResults = new TestResults(ModelNameTextBox.Text);
    _timer = new System.Threading.Timer(UpdateCounts, null, 0, 500);            
}

private void UpdateCounts(object info)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        PassCountLabel.Text = _testResults.PassedCount.ToString();
        RequestCountLabel.Text = _testResults.RequestedCount.ToString();                
    }));
}
但一旦删除Dispatcher.CurrentDispatcher,它就可以正常工作:

private void UpdateCounts(object info)
{
    BeginInvoke(new Action(() =>
    {
        PassCountLabel.Text = _testResults.PassedCount.ToString();
        RequestCountLabel.Text = _testResults.RequestedCount.ToString();                
    }));
}
Dispatcher.CurrentDispatcher.BeginInvoke仅当您从UI线程调用它时有效,否则它将调用当前线程


您必须使用Application.Current.Dispatcher来调用UI线程。

您不能像这样任意混合WPF和Winforms代码。您的Main()入口点似乎使用了Application.Run()的Winforms版本。使用Dispatcher将无法运行任何代码,因为应用程序中没有Dispatcher循环。如果这是有意的,换句话说,这段代码在一个库中,您不能假设它是使用库的WPF还是Winforms应用程序,那么您必须以非常不同的方式执行。您必须在构造函数中复制SynchronizationContext.Current。但同样,更新库中的控件是不好的。不要混在一起。