繁体   English   中英

从后台线程更新UI

[英]Update UI from background Thread

这只是一个奇怪的问题。 哪一种是从另一个线程更新UI的最佳方法。 首先,这个:

private delegate void MyDelegateMethod();
void MyMethod()
{
    if (unknowncontrol.InvokeRequired)
    {
        this.BeginInvoke(new MyDelegateMethod(MyMethod));
        return;
    }
    unknowncontrol.property = "updating!";
}

另一方面:

Invoke((System.Threading.ThreadStart)delegate()
{
    unknowncontrol.property = "updating!";
});

还是有更好的方法来做到这一点?

当然,这是针对WinForms的,对于WPF,则是调度程序。 WPF的代码如何?

我问,因为过去,使用上述两个选项从引发的事件更新UI时遇到错误。 这类错误,例如:“没有可用的源代码”。 我想我们所有人都看过他们:D。

感谢,并有一个愉快的一天!

在此查看Roy Osherove的博客文章: http ://osherove.com/blog/2006/3/1/the-3-ways-to-create-a-thread-safe-gui-with-net-20-with -one.html

delegate void Func<T>(T t);
Func del = delegate
{

  // UI Code goes here
};
Invoke(del);

默认的Action代表90%的时间都在工作:

private void Log(String value)
{
    // Verify that we're on the same thread
    if (textBox1.InvokeRequired)
    {
        // We're not on the same thread - Invoke the UI thread
        textBox1.Invoke(new Action<string>(Log), value);
        return;
    }

    // We're on the same thread - Update UI
    textBox1.Text += value + "\r\n";
}

private void OnSomethingHappened()
{
    Log("Something happened!");
}

使用[Dispatcher.Invoke(DispatcherPriority,Delegate)]可以从另一个线程或后台更改UI。

步骤1 使用以下名称空间

using System.Windows;
using System.Threading;
using System.Windows.Threading;

第二步 将以下行放在需要更新UI的位置

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

句法

 [BrowsableAttribute(false)] public object Invoke( DispatcherPriority priority, Delegate method ) 

参量

priority

类型: System.Windows.Threading.DispatcherPriority

相对于Dispatcher事件队列中其他未决操作的优先级,将调用指定的方法。

method

类型: System.Delegate

一个不带参数的方法的委托,该委托被推送到Dispatcher事件队列中。

返回值

类型: System.Object

被调用委托的返回值;如果委托没有返回值,则返回null。

版本信息

自.NET Framework 3.0起可用

我通常使用第一个模型,但这只是因为我发现它更清晰。 两者之间并没有真正的有效区别。

如我所见,最好的方法是设置ui元素的属性绑定到的CLR属性。

第一种方法(BeginInvoke)确保UI更新代码在创建控件的同一线程上执行。 第二种方法没有。 使所有UI更新代码在同一线程上执行可以避免很多线程问题,并允许您使用不一定是线程安全的控件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM