问题描述
我在更新c#的进度栏和文本框时遇到问题.
当我尝试此代码时
I have a problem in updating the progressbar and textbox at c#.
when i tried this code
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "1";
for (int i = 1; i < 11; i++)
{
textBox1.Text = (int.Parse(textBox1.Text) + 1).ToString();
textBox1.Refresh();
progressBar1.Value += 10;
progressBar1.Refresh();
Thread.Sleep(2000);
}
}
}
}
文本框和进度条的更新工作正常,并且文本很好地定期出现在文本框上.
我制作了一个具有服务器和客户端的程序,可以将文件从客户端发送到服务器
我做到了,效果很好,并在200 Mb的文件上尝试过
当我尝试制作进度条并在发送和接收操作期间将其取消时,它无法正常工作,直到程序末尾突然达到100%时,它仍然没有进展,我试图将值输出到文本框,但文本没有直到程序结束出现
当我尝试调试时,我发现文本框的文本和progressbar值正在按我的意愿进行更新,但是为什么直到程序结束它们才起作用?这是我的问题
我在其中使用进度条的那段代码
the updating of textbox and progress bar work fine and the text appear on the textbox periodically very well.
i made a program that has server and client to send a file from client to server
i did it and it work very well and i tried it on a file with size 200 Mb
when i tried to make a progressbar and apdate it during the sending and receiving operation it disnot work, it still not progress untill the end of the program go to 100 % suddenly i tried to out the value to a textbox but the text of it not appear untill the end of the program
when i tried to debug i found that the text of the textbox and the progressbar value was updating as i want but why they had no effect untill the end of the program? it is my question
the piece of code that i used the progress bar in is there
//it is a part of the sender of the file
int i = 1;
int value = 0;
remainsize = totalsize;//totalsize is the size of the file
while (remainsize > 1024)
{
data = new byte[1024];
myfile.Read(data, 0, 1024);//read 1K from the file
myclient.Client.Send(data);//send the data to the receiver
data = new byte[2];
myclient.Client.Receive(data);//wait for OK from the receiver
if (Encoding.ASCII.GetString(data) != "OK")
{
MessageBox.Show("SOMETHING WRONG!!");
myclient.Close();
this.Close();
Application.Exit();
}
remainsize -= 1024;
value+=5;/*increment value here with 5 to test i will update it in my code after solving it*/
textBox3.Text = value.ToString();//update the textbox
textBox3.Refresh();//refresh it to appear the text ///do not appear any thing
progressbar1.value=value;//update the value of the progressbar
progressbar1.Refresh();
System.Threading.Thread.Sleep(2000);/* thought the problem in timing and i used this but with no use*/
如果您要我上传所有项目,请告诉我,我将执行此操作
if you want me to upload all the project tell me and i will do this
推荐答案
...
this.Invoke(new MethodInvoker(delegate
{
textBox1.Text = (int.Parse(textBox1.Text) + 1).ToString();
textBox1.Refresh();
progressBar1.Value += 10;
progressBar1.Refresh();
}));
...
问候
Robert
Regards
Robert
这篇关于进度栏中的问题我无法解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!