C#进度条实现之异步实例浅析

C#进度条实现之异步实例浅析

2009-08-17 14:36 Deckard 博客园 我要评论(0) 字号:T | T


C#进度条实现之异步实例是如何实现的呢?C#进度条实现之异步实例需要注意的是什么呢?那么本文就向你介绍C#进度条实现之异步实例的具体事宜。

AD:


C#进度条实现之异步实例是如何展示C#进度条实现的呢?让我们来看看:

C#进度条实现之异步实例进度条页面:

  1. //====================================  
  2. // Microsoft patterns & practices  
  3. // CompositeUI Application Block  
  4. //====================================  
  5. // Copyright ?Microsoft Corporation.    
  6. //All rights reserved.  
  7. // THIS CODE AND INFORMATION IS   
  8. //PROVIDED "AS IS" WITHOUT WARRANTY  
  9. // OF ANY KIND, EITHER EXPRESSED OR   
  10. //IMPLIED, INCLUDING BUT NOT  
  11. // LIMITED TO THE IMPLIED WARRANTIES  
  12. // OF MERCHANTABILITY AND  
  13. // FITNESS FOR A PARTICULAR PURPOSE.  
  14. //=====================================  
  15.  
  16. using System;  
  17. using System.Collections.Generic;  
  18. using System.ComponentModel;  
  19. using System.Data;  
  20. using System.Drawing;  
  21. using System.Text;  
  22. using System.Windows.Forms;  
  23.  
  24.  
  25. namespace BackgroudWokerUI  
  26. {  
  27. public partial class ProgressForm : Form  
  28. {  
  29. public ProgressForm()  
  30. {  
  31. InitializeComponent();  
  32. }  
  33.  
  34. //工作完成后执行的事件  
  35. public void OnProcessCompleted(object sender, EventArgs e)  
  36. {  
  37. this.Close();  
  38. }  
  39.  
  40. //工作中执行进度更新  ,C#进度条实现之异步实例
  41. public void OnProgressChanged(
  42. object sender, ProgressChangedEventArgs e)  
  43. {  
  44. progressWork.Value = e.ProgressPercentage;  
  45. }  
  46.  
  47. private void btnClose_Click(object sender, EventArgs e)  
  48. {  
  49. Close();  
  50. }  
  51. }  

C#进度条实现之异步实例主页面:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Threading;  
  9.  
  10. //Note You must be careful not to manipulate any user-interface objects   
  11. //in your System.ComponentModel.BackgroundWorker.DoWork event handler.   
  12. //Instead, communicate to the user interface through the   
  13. //System.ComponentModel.BackgroundWorker.ProgressChanged and   
  14. //System.ComponentModel.BackgroundWorker.RunWorkerCompleted events.  
  15.  
  16. namespace BackgroudWokerUI  
  17. {  
  18. public partial class MainForm : Form  
  19. {  
  20. //BindingList is useful list for UI   
  21. private IList<string> leftList = new BindingList<string>();  
  22. private IList<string> rightList = new BindingList<string>();  
  23.  
  24. private BackgroundWorker worker = null;  
  25.  
  26. public MainForm()  
  27. {  
  28. InitializeComponent();  
  29. //Databinding here  
  30. listBox1.DataSource = leftList;  
  31. listBox2.DataSource = rightList;  
  32. }  
  33.  
  34. private void addButton_Click(object sender, EventArgs e)  
  35. {  
  36. if (textBox.Text.Length != 0)  
  37. {  
  38. leftList.Add(textBox.Text);  
  39. textBox.Text = "";  
  40. textBox.Focus();  
  41. }  
  42. }  
  43.  
  44. private void moveButton_Click(object sender, EventArgs e)  
  45. {  
  46. //显示进度条  ,C#进度条实现之异步实例
  47. ProgressForm progressForm = new ProgressForm();  
  48. progressForm.Show();  
  49.  
  50. // Prepare the background worker   
  51. //for asynchronous prime number calculation  
  52. //准备进度条的记数  
  53. worker= new BackgroundWorker();  
  54. // Specify that the background   
  55. //worker provides progress notifications    
  56. //指定提供进度通知  
  57. worker.WorkerReportsProgress = true;  
  58. // Specify that the background worker supports cancellation  
  59. //提供中断功能  
  60. worker.WorkerSupportsCancellation = true;  
  61. // The DoWork event handler is the main   
  62. //work function of the background thread  
  63. //线程的主要功能是处理事件  
  64. //开启线程执行工作  ,C#进度条实现之异步实例
  65. worker.DoWork += new DoWorkEventHandler(worker_DoWork);  
  66. // Specify the function to use to handle progress  
  67. //指定使用的功能来处理进度  
  68. worker.ProgressChanged +=   
  69. new ProgressChangedEventHandler(worker_ProgressChanged);  
  70. worker.ProgressChanged +=   
  71. new ProgressChangedEventHandler(progressForm.OnProgressChanged);  
  72. // Specify the function to run when the   
  73. //background worker finishes  
  74. // There are three conditions possible   
  75. //that should be handled in this function:  
  76. // 1. The work completed successfully  
  77. // 2. The work aborted with errors  
  78. // 3. The user cancelled the process  
  79. //进度条结束完成工作  
  80. //1.工作完成  
  81. //2.工作错误异常  
  82. //3.取消工作  
  83. worker.RunWorkerCompleted +=   
  84. new RunWorkerCompletedEventHandler(  
  85. worker_RunWorkerCompleted);  
  86. worker.RunWorkerCompleted+=  
  87. new RunWorkerCompletedEventHandler(  
  88. progressForm.OnProcessCompleted);  
  89.    
  90. //If your background operation requires a parameter,   
  91. //call System.ComponentModel.BackgroundWorker.RunWorkerAsync   
  92. //with your parameter. Inside   
  93. //the System.ComponentModel.BackgroundWorker.DoWork   
  94. //event handler, you can extract the parameter from the   
  95. //System.ComponentModel.DoWorkEventArgs.Argument property.  
  96. //如果进度条需要参数  
  97. //调用System.ComponentModel.BackgroundWorker.RunWorkerAsync  
  98. //传入你的参数至System.ComponentModel.BackgroundWorker.DoWork   
  99. //提取参数  
  100. //System.ComponentModel.DoWorkEventArgs.Argument   
  101. worker.RunWorkerAsync(leftList);  
  102. }  
  103.  
  104. //单线程执行工作  
  105. private void worker_DoWork(
  106. object sender, DoWorkEventArgs e)  
  107. {  
  108. MoveList((BackgroundWorker)sender,e);  
  109. }  
  110.  
  111. //进行转移工作  
  112. private void MoveList(
  113. BackgroundWorker worker,DoWorkEventArgs e)  
  114. {  
  115. IList<string> list = e.Argument as IList<string>;  
  116.  
  117. for (int i = 0; i < list.Count; i++)  
  118. {  
  119. // Check for cancellation  
  120. //检查取消  
  121. if (worker.CancellationPending)  
  122. {  
  123. e.Cancel = true;  
  124. break;  
  125. }  
  126. else 
  127. {  
  128. // This will be handled in the correct thread thanks to the   
  129. // internals of BackgroundWroker and AsyncOperation  
  130. worker.ReportProgress((i + 1) * (100 / list.Count), list[i]);  
  131. // Simulate some time consuming proccess.  
  132. //线程休眠  
  133. Thread.Sleep(500);  
  134. }  
  135. }  
  136. }  
  137. //添加数据至右边listBox  
  138. private void worker_ProgressChanged(  
  139. object sender, ProgressChangedEventArgs e)  
  140. {  
  141. //Add string to the right listBox  
  142. rightList.Add(e.UserState as string);  
  143. }  
  144.  //C#进度条实现之异步实例
  145. //工作完成状态  
  146. private void worker_RunWorkerCompleted(  
  147. object sender, RunWorkerCompletedEventArgs e)  
  148. {  
  149. if (e.Cancelled)  
  150. {  
  151. label.Text = "Cancelled!取消";  
  152. }  
  153. else if (e.Error != null)  
  154. {  
  155. label.Text = "Error!异常";  
  156. }  
  157. else 
  158. {  
  159. label.Text = "Success!完成";  
  160. leftList.Clear();  
  161. }  
  162. }  
  163. //取消中  
  164. private void cancelButton_Click(  
  165. object sender, EventArgs e)  
  166. {  
  167. if (worker.IsBusy)  
  168. {  
  169. label.Text = "Cancelling...";  
  170. //挂起进程  
  171. worker.CancelAsync();  
  172. }  
  173. }  
  174. //返回操作  
  175. private void moveBackButton_Click(  
  176. object sender, EventArgs e)  
  177. {  
  178. foreach (string str in rightList)  
  179. {  
  180. leftList.Add(str);  
  181. }  
  182. rightList.Clear();  
  183. }  
  184. }  

C#进度条实现之异步实例的相关内容就向你介绍到这里,希望对你了解和学习C#进度条实现有所帮助。

【编辑推荐】

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用.NET Framework 3.5实现异步编程的示例: ```csharp using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Main thread started."); // 使用委托和回调函数实现异步编程 Console.WriteLine("Using delegate and callback to implement asynchronous programming."); MyDelegate myDelegate = new MyDelegate(DoSomething); myDelegate.BeginInvoke(5000, new AsyncCallback(Callback), null); // 使用线程池实现异步编程 Console.WriteLine("Using thread pool to implement asynchronous programming."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomethingThreadPool), 3000); // 使用异步方法实现异步编程 Console.WriteLine("Using async method to implement asynchronous programming."); DoSomethingAsync(2000); Console.WriteLine("Main thread ended."); Console.ReadLine(); } // 定义委托和回调函数 public delegate void MyDelegate(int milliseconds); public static void DoSomething(int milliseconds) { Console.WriteLine("DoSomething started."); Thread.Sleep(milliseconds); Console.WriteLine("DoSomething completed."); } public static void Callback(IAsyncResult ar) { Console.WriteLine("Callback started."); MyDelegate myDelegate = (MyDelegate)ar.AsyncState; myDelegate.EndInvoke(ar); Console.WriteLine("Callback completed."); } // 使用线程池 public static void DoSomethingThreadPool(object state) { Console.WriteLine("DoSomethingThreadPool started."); int milliseconds = (int)state; Thread.Sleep(milliseconds); Console.WriteLine("DoSomethingThreadPool completed."); } // 使用异步方法 public static async void DoSomethingAsync(int milliseconds) { Console.WriteLine("DoSomethingAsync started."); await Task.Run(() => Thread.Sleep(milliseconds)); Console.WriteLine("DoSomethingAsync completed."); } } ``` 该示例使用了三种不同的方法来实现异步编程:使用委托和回调函数、使用线程池、使用异步方法。在每种方法中,都使用Thread.Sleep方法模拟耗时操作。注意,在使用异步方法时,需要使用async和await关键字来标记异步方法和等待异步操作完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值