Showing Progress Bar until the data is received from the server C#

别等时光非礼了梦想. 提交于 2019-12-31 03:50:27

问题


I have a made a small tool which gets file size and name of the URL but it takes time (approx 4 seconds) when I run the code and enter a file URL it takes time for the user it will look like it is not working.

I want to show a progress bar until the data is received so that user may not think that the application is not working.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Multi_Tool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("You have not typed the URL", "URL Error",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    string URL = textBox1.Text;
                    string filetype = URL.Substring(URL.LastIndexOf(".") + 1,
                            (URL.Length - URL.LastIndexOf(".") - 1));
                    FileType.Text = filetype.ToUpper();
                    string filename = URL.Substring(URL.LastIndexOf("/") + 1,
                            (URL.Length - URL.LastIndexOf("/") - 1));
                    namelabel.Text = filename;
                    System.Net.WebRequest req = System.Net.HttpWebRequest.Create(textBox1.Text);
                    req.Method = "HEAD";
                    System.Net.WebResponse resp = req.GetResponse();
                    long ContentLength = 0;
                    long result;
                    if (long.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
                    {
                        string File_Size;

                        if (ContentLength >= 1073741824)
                        {
                            result = ContentLength / 1073741824;
                            kbmbgb.Text = "GB";
                        }
                        else if (ContentLength >= 1048576)
                        {
                            result = ContentLength / 1048576;
                            kbmbgb.Text = "MB";
                        }
                        else
                        {
                            result = ContentLength / 1024;
                            kbmbgb.Text = "KB";
                        }
                        File_Size = result.ToString("0.00");
                        sizevaluelabel.Text = File_Size;
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear(); 
        }  
    }
}


回答1:


You can use a background worker to move your downloading to another thread and showing a progress bar until the data is received.

ProgressForm is a form which contains progress bar which you can show until data is downloaded

this.progressBar1 = new System.Windows.Forms.ProgressBar();
// 
// progressBar1
// 
this.progressBar1.Location = new System.Drawing.Point(12, 30);
this.progressBar1.MarqueeAnimationSpeed = 1;
this.progressBar1.Maximum = 2500;
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(522, 23);
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar1.TabIndex = 1;


//constructor
public frmProgress(string text)
{
   this.Text = text;
   InitializeComponent();
}

If you want to show value in your progress bar make sure to change the properties back to normal(which are set as marquee in answer as of now).But as you said it is going to take just 4 secs it would be good to use marquee

//Method to increment value of progress bar
public void PrgBarInc()
{
  if (this.IsHandleCreated)
  {
    if (this.InvokeRequired)
    {
       this.Invoke(new MethodInvoker(PrgBarInc));
    }
    else
    {
       prgBar.Increment("your val");
    }
}

==============================Main UI class==============================

BackgroundWorker backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

//Add In your method which initiates download 
public void PerformDownload()
{
  ProgressForm = new frmProgress("your text");
  ProgressForm.ShowInTaskbar = false;
  backgroundWorker1.RunWorkerAsync();
  ProgressForm.ShowDialog();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   //perform service request
   //if any of your task gets compeleted just call
   //ProgressForm.PrgBarInc()
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    ProgressForm.Close();
    ProgressForm.Dispose();
}



回答2:


Normally, you update the progress bar like this:

progressBar1.Value = N;

Wrapping it within BeginInvoke() makes the UI responsive:

Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    new DispatcherOperationCallback(delegate
               {
                   progressBar1.Value = progressBar1.Value + 1;
                   //update in UI Thread
                   return null;
               }), null);


来源:https://stackoverflow.com/questions/49527050/showing-progress-bar-until-the-data-is-received-from-the-server-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!