在C#windows应用程序中显示循环内的文本
我的windows窗体中有一个循环 在循环内,我应该显示在循环内处理的客户编号 但是在循环过程中,应该包含客户编号的文本框会冻结,并且在循环完成之前不会显示任何文本框 任何IDE如何解决此问题?您需要刷新()文本框以获得更新的customerID 试试这个:在C#windows应用程序中显示循环内的文本,c#,windows,loops,C#,Windows,Loops,我的windows窗体中有一个循环 在循环内,我应该显示在循环内处理的客户编号 但是在循环过程中,应该包含客户编号的文本框会冻结,并且在循环完成之前不会显示任何文本框 任何IDE如何解决此问题?您需要刷新()文本框以获得更新的customerID 试试这个: private void button1_Click(object sender, EventArgs e) { Int16 customerID = 5000; for(Int16 i=0;i<=10000;i++
private void button1_Click(object sender, EventArgs e)
{
Int16 customerID = 5000;
for(Int16 i=0;i<=10000;i++)
{
textBox1.Text = customerID.ToString();
customerID++;
textBox1.Refresh(); //this line will update show new value in textbox
}
}
我希望它可能会有所帮助尝试以下方法:
private void button1_Click(object sender, EventArgs e)
{
Int16 customerID = 5000;
for(Int16 i=0;i<=10000;i++)
{
textBox1.Text = customerID.ToString();
customerID++;
textBox1.Refresh(); //this line will update show new value in textbox
}
}
完整参考是System.Threading.Tasks.Task
,或使用,System.Threading.Tasks
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
// Any GUI control which you want to use within thread,
// you need Invoke using GUI thread. I have declare a method below for this
//Now use this method as
ExecuteSecure(() => textBox1.Text = "Customer Id " + i);
//... other code etc.
Thread.Sleep(1000);
}
});
//---
private void ExecuteSecure(Action action)
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(() => action()));
}
else
{
action();
}
}
Task.Factory.StartNew(()=>
{
对于(int i=0;i<10;i++)
{
//要在线程中使用的任何GUI控件,
//您需要使用GUI线程进行调用
//现在将此方法用作
ExecuteSecure(()=>textBox1.Text=“客户Id”+i);
//…其他代码等。
睡眠(1000);
}
});
//---
私有void ExecuteSecure(操作)
{
如果(需要调用)
{
调用(newmethodinvoker(()=>action());
}
其他的
{
动作();
}
}
或者使用BackgroundWorker
如果您希望实时更新您的UI
,我收到此错误错误1当前上下文中不存在名称“Task”sProj\Form1.cs 86 17Task.Factory
仅在.NET Framework 4
中引入。您的.Net版本是什么?@asmgx完整参考是System.Threading.Tasks.Task
,或者使用System.Threading.Tasks
。尝试在循环中显示内容不是一个好主意。UI必须在每次迭代时重新绘制,循环将移动到快速,以便显示可见。向我们展示错误代码,也许我们可以找到解决方法。