我需要在单击按钮后不断更新我的文本框,但按钮应该按原样执行其剩余任务。
简单的是,当点击事件发生时,文本框不应该等待点击事件完成,而是开始不断更新它的文本。
示例代码
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
}
}
}
}
重要::当它执行事件“Cthread.start();”时文本框应立即开始更新文本,而单击事件的其余功能(如“while 循环”)应并行执行。
最佳答案
如果这是在 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
}
}
希望这对你有帮助,虽然晚了.. :)
关于c# - 如何在不按住 Windows 窗体应用程序 C# 中的按钮的情况下连续更新文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10654121/