你想通过进展来思考什么? 而是下载档案(因为其大部)或处理档案?
Progress bar reflecting processing file
你的进步阻碍着变革,因为你的方法是同步的,否则就没有实现。 <代码>BackgroundWorker 类别完全针对这类问题设计。 它的主要工作是同步进行的,并且能够报告进展已经发生变化。 这里是如何改变旅行路线,以便使用:
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
string url = "http://api.bing.net/xml.aspx?AppId=XXX&Query=" + text + "&Sources=Translation&Version=2.2&Market=en-us&Translation.SourceLanguage=en&Translation.TargetLanguage=De";
XmlDocument xml = new XmlDocument();
xml.Load(url);
XmlNodeList node = xml.GetElementsByTagName("tra:TranslatedTerm");
BackgroundWorker worker = new BackgroundWorker();
// tell the background worker it can report progress
worker.WorkerReportsProgress = true;
// add our event handlers
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(this.ProgressChanged);
worker.DoWork += new DoWorkEventHandler(this.DoWork);
// start the worker thread
worker.RunWorkerAsync(node);
}
现在,主要部分:
private void DoWork(object sender, DoWorkEventArgs e)
{
// get a reference to the worker that started this request
BackgroundWorker workerSender = sender as BackgroundWorker;
// get a node list from agrument passed to RunWorkerAsync
XmlNodeList node = e.Argument as XmlNodeList;
for (int i = 0; x < node.Count; i++)
{
textBox2.Text = node[i].InnerText;
workerSender.ReportProgress(node.Count / i);
}
}
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// do something after work is completed
}
public void ProgressChanged( object sender, ProgressChangedEventArgs e )
{
progressBar.Value = e.ProgressPercentage;
}
Progress bar reflecting downloading file
Try using HttpWebRequest
to have the file as a stream.
// Create a WebRequest object with the specified url.
WebRequest myWebRequest = WebRequest.Create(url);
// Send the WebRequest and wait for response.
WebResponse myWebResponse = myWebRequest.GetResponse();
// Obtain a Stream object associated with the response object.
Stream myStream = myWebResponse.GetResponseStream();
long myStreamLenght = myWebResponse.ContentLength;
So now you know the length of this XML file. Then you have to asynchronously read the content from stream (BackgroundWorker
and StreamReader
is a good idea). Use myStream.Position
and myStreamLenght
to calculate the progress.
I know that I m not very specific but I just wanted to put you in the right direction. I think it doesn t make sense to write about all those things here. Here you have links that will help you dealing with Stream
and BackgroundWorker
: