Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 4th, 2012  |  syntax: None  |  size: 5.07 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to fix form lagging when its labels changes by a thread?
  2. Thread thS = new Thread(timeElasped);
  3. thS.Start();   //this code runs when the form show up
  4.        
  5. private void timeElasped()
  6.     {
  7.         int counter = 0;
  8.         while (fileTransfer.busy)
  9.         {
  10.             rate = (fileTransfer.sum - prevSum);
  11.             RateLabel(string.Format("{0}/Sec", CnvrtUnit(rate)));
  12.             if(rate!=0)
  13.                 left = (fileTransfer.fileSize - fileTransfer.sum) / rate;
  14.             prevSum = fileTransfer.sum;
  15.             TimeSpan t = TimeSpan.FromSeconds(left);
  16.             timeLeftLabel(FormatRemainingText(rate, t));
  17.             TimeSpan Duration = TimeSpan.FromSeconds(counter);
  18.             ElapsedLabel(string.Format("{0:D2}:{1:D2}:{2:D2}", Duration.Hours, Duration.Minutes, Duration.Seconds));
  19.             counter++;
  20.             Thread.Sleep(1000);
  21.         }
  22.     }
  23.        
  24. public static void sendFile(string filePath)
  25.     {
  26.         //initialize a thread for progress form
  27.         Thread thFP = new Thread(fpRUN);
  28.         FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  29.         string fileName = Path.GetFileName(filePath);
  30.         byte[] fileData;
  31.         try
  32.         {
  33.             //sending file name and file size to the server
  34.             busy = true;
  35.             fileSize = fs.Length;
  36.             byte[] fileDetial = null;
  37.             string detail =  fileName + "," + fileSize.ToString();
  38.             fileDetial = Encoding.ASCII.GetBytes(detail);
  39.             client.Send(fileDetial);
  40.  
  41.             //sending file data to the server
  42.  
  43.             fileData = new byte[packetSize];
  44.             count = 0;
  45.             sum = 0;                          
  46.             // running transfer rate
  47.             fileProgress fP = new fileProgress("Sending...");
  48.             //show the progress form
  49.             thFP.Start(fP);
  50.  
  51.             while (sum < fileSize)
  52.             {
  53.                 fP.ProgressBarFileHandler(sum, fileSize);
  54.                 fs.Seek(sum, SeekOrigin.Begin);
  55.                 fs.Read(fileData, 0, fileData.Length);
  56.                 count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
  57.                 sum += count;
  58.             }
  59.         }
  60.         finally
  61.         {
  62.             busy = false;
  63.             fs.Close();
  64.             fileData = null;
  65.             MessageBox.Show(string.Format("{0} sent successfully", fileName));
  66.         }
  67.     }
  68.        
  69. public partial class Form1 : Form
  70. {
  71.     private Worker worker;
  72.  
  73.     public Form1()
  74.     {
  75.         InitializeComponent();
  76.     }
  77.  
  78.     private void button1_Click(object sender, EventArgs e)
  79.     {
  80.         worker = new Worker();
  81.         worker.ProgressUpdated += this.worker_ProgressUpdated;
  82.         worker.WorkDone += this.worker_WorkDone;
  83.         worker.Start();
  84.     }
  85.  
  86.     private void worker_WorkDone(object sender, EventArgs e)
  87.     {
  88.         // Detaches event handlers
  89.         // /! Will be called from a thread different than the UI thread
  90.         worker.ProgressUpdated -= this.worker_ProgressUpdated;
  91.         worker.WorkDone -= this.worker_WorkDone;
  92.     }
  93.  
  94.     private void worker_ProgressUpdated(object sender, ProgressEventArgs e)
  95.     {
  96.         // Updates the UI
  97.         // /! Will be called from a thread different than the UI thread
  98.         this.SetLabelText(string.Format("Percentage: {0}", ((double)e.Value * 100 / (e.Max - e.Min))));
  99.     }
  100.  
  101.     private void SetLabelText(string text)
  102.     {
  103.         // Following required if the method is called from a thread that is not the UI thread
  104.         if (this.label1.InvokeRequired)
  105.         {
  106.             this.label1.Invoke(new MethodInvoker(() => this.SetLabelText(text)));
  107.         }
  108.         else
  109.         {
  110.             this.label1.Text = text;
  111.         }
  112.     }
  113. }
  114.        
  115. public class ProgressEventArgs : EventArgs
  116. {
  117.     public int Value { get; set; }
  118.  
  119.     public int Max { get; set; }
  120.  
  121.     public int Min { get; set; }
  122. }
  123.  
  124. public class Worker
  125. {
  126.     public delegate void ProgressUpdatedEventHandler(object sender, ProgressEventArgs e);
  127.  
  128.     public event ProgressUpdatedEventHandler ProgressUpdated;
  129.  
  130.     public event EventHandler WorkDone;
  131.  
  132.     public void Start()
  133.     {
  134.         Thread workerThread = new Thread(new ThreadStart(this.DoWork));
  135.         workerThread.Start();
  136.     }
  137.  
  138.     private void DoWork()
  139.     {
  140.         int min = 0;
  141.         int max = 1000000;
  142.  
  143.         for (int i = min; i < max; i++)
  144.         {
  145.             // Simulates work
  146.             ////System.Threading.Thread.Sleep(1);
  147.  
  148.             // Notify of progress update
  149.             ////this.OnProgressUpdate(min, max, i);
  150.  
  151.             // Notify of progress update but not every time to save CPU time
  152.             // Uses mod function to do the job 1 out of 100 times
  153.             if (i % 100 == 0)
  154.             {
  155.                 this.OnProgressUpdate(min, max, i);
  156.             }
  157.         }
  158.  
  159.         // Notify the work is done
  160.         if (this.WorkDone != null)
  161.         {
  162.             this.WorkDone(this, EventArgs.Empty);
  163.         }
  164.     }
  165.  
  166.     private void OnProgressUpdate(int min, int max, int value)
  167.     {
  168.         if (this.ProgressUpdated != null)
  169.         {
  170.             this.ProgressUpdated(this, new ProgressEventArgs { Max = max, Min = min, Value = value });
  171.         }
  172.     }
  173. }