在按钮单击时在C#更新UI中 [英] In C# update UI while in a button click

查看:77
本文介绍了在按钮单击时在C#更新UI中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我点击了一个按钮,运行了很多代码。我希望在代码运行时更新我的​​UI。它从按钮单击返回后更新。我可以在按钮点击时显示消息吗?



老家伙。

I have a button click that runs a lot of code. I would like to updata my UI while that code is running. It updates after the return from the button click. Can I display messages while in the button click?

Old guy.

推荐答案

你需要执行这个代码在一些单独的线程中,而不是在你的UI线程中。但现在......



您无法从非UI线程调用与UI相关的任何内容。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke() [ ^ ],

使用Treeview扫描仪和MD5的问题 [ ^ ]。



另请参阅有关线程的更多参考资料:

如何让keydown事件在不同的操作上运行vb.net中的线程 [ ^ ],

在启用禁用+多线程后控制事件未触发 [ ^ ]。







这些是我如何以非常强大的方式获取和封装线程的答案:

如何将ref参数传递给主题 [ ^ ],

在线程(生产者)启动后更改线程(生产者)的参数 [ ^ ],

C#中的MultiThreading [< a href =http://www.codeproject.com/Answers/485734/MultiThreadingplusinplusC-23#answer4target =_ blanktitle =New Window> ^ ]。







一个大警告:很多人建议使用 Application.DoEvent 而不是线程。 不要这样做。在某种程度上,它可以工作,但更好地避免麻烦和浪费你的时间。太久无法解释......



-SA
You need to execute this code in some separate thread, not in your UI thread. But now…

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].



And these are my answers on how to get and encapsulate a thread in a very robust way:
How to pass ref parameter to the thread[^],
change paramters of thread (producer) after it started[^],
MultiThreading in C#[^].



A big warning: Many advise to use Application.DoEvent instead of thread. Don''t do it. To certain extent, it can work, but better stay out of trouble and waste of your time. Too long to explain…

—SA


你好,





您应该尝试使用backgroundworker类来执行此操作。



设置DoWork事件处理程序和把你的按钮所做的长代码放入其中。在代码中而不是更新UI只需引发事件ReportProgress并传递更新此UI所需的数据。



设置ProgressChanged事件处理程序。这个事件将从后台工作线程接收通知,您可以在其中安全地更新UI。





这是一个例如:



Hello,


You should try using the backgroundworker class to do this.

Setup a DoWork event handler and put in it the long code that your button is doing. In your code instead of updating the UI just raise an event ReportProgress and pass the data needed to update this UI.

Setup a ProgressChanged event handler. This is this event that will receive notifications from the background worker thread and in which you can safely update the UI.


Here is an example:

public Form1()
{
    InitializeComponent();
    backWkr.WorkerReportsProgress = true;
    backWkr.ProgressChanged += backWkr_ProgressChanged;
    backWkr.DoWork += backWkr_DoWork;
}

BackgroundWorker backWkr = new BackgroundWorker();

private void button1_Click(object sender, EventArgs e)
{
    backWkr.RunWorkerAsync();
}

void backWkr_DoWork(object sender, DoWorkEventArgs e)
{
    // the code that take tsome time to execute.
    int percentProgress = 0;
    do
    {
        percentProgress++;
        // simulate some long operation...
        Thread.Sleep(100);
        object whatEverIsNeeded = "blah blah blah";
        backWkr.ReportProgress(percentProgress, whatEverIsNeeded);
    } while (percentProgress < 100 );
}

void backWkr_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // get the data...
    object whatEverStatepassed = e.UserState;
    int percent = e.ProgressPercentage;
    // update ui, do something... eyc...
    this.BackColor = Color.FromArgb(this.BackColor.R, this.BackColor.G, percent);
}





Valery。



Valery.


这篇关于在按钮单击时在C#更新UI中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆