如何在 Windows 窗体应用程序 C# 中连续更新文本框而不停止按钮?

Aze*_*ram 1 c# multithreading event-handling multitasking

单击按钮后,我需要不断更新文本框,但按钮应按原样执行其余任务。

简单的是,当执行单击事件时,文本框不应等待单击事件完成,而是开始不断更新其文本。

示例代码

using System.threading;

namespace name
{
    public class sA
    {
        public void th()
        {
           textbox.invoke(new MethodInvoke(()=> textbox.AppendText("hello\n")));
        }

        private void Button1Click(object sender, EventArgs e)
        {
           thread cThread=new thread(th);
           cThread.start();

           while(true)
           {
               // do any thing
           }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

重要:: 当它执行事件“ Cthread.start();”时 文本框应立即开始更新文本,而单击事件的其余功能(如“while 循环”)应并行执行。

在此输入图像描述

小智 5

如果这是在 Windows 窗体内..然后添加Application.DoEvents();到循环中的任意位置,例如

private void Button1Click(object sender, EventArgs e)
{
   thread cThread=new thread(th);
   cThread.start();
   while(true)
   {
     // do any thing   
     textbox.Invalidate();
     Application.DoEvents(); // Releases the current thread back to windows form
                          // NOTE Thread sleep different in Application.DoEvents();
                          //Application.DoEvents() is available only in System.Windows.Forms
   }
} 
Run Code Online (Sandbox Code Playgroud)

希望这对你有帮助,虽然晚了..:)