C#基本异步操作
2015-07-28 16:28
483 查看
工程链接:
http://pan.baidu.com/s/1mgEdsRe
</pre><pre name="code" class="csharp">using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Numerics; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace AsynProgram { /// <summary> /// partial关键字表示为类的分部分 /// </summary> public partial class Window : Form { private Object lockObj = new object(); static int number = 10; public Window() { InitializeComponent(); this.progressLabel.Visible = false; } private void Syn_Button_Click(object sender, EventArgs e) { this.progressLabel.Visible = true; this.Syn_Button.Enabled = this.Asyn_Button.Enabled= false; while(this.progressBar.Value!=100) { this.progressBar.Value += 1; this.progressLabel.Text = "正在加载中:" + progressBar.Value + "%..."; Thread.Sleep(50); } this.progressBar.Value = 0; this.Syn_Button.Enabled = this.Asyn_Button.Enabled = true; this.progressLabel.Visible = false; } private void Asyn_Button_Click(object sender, EventArgs e) { this.progressLabel.Visible = true; this.Syn_Button.Enabled = this.Asyn_Button.Enabled = false; Thread myThread = new Thread(DoWork); myThread.Start(); } void DoWork() { int n = 0; while (++n<100) { this.BeginInvoke(new Action(() => { this.progressBar.Value =n; this.progressLabel.Text = "正在加载中:" + progressBar.Value + "%..."; })); Thread.Sleep(50); } this.BeginInvoke(new Action(() => { this.progressBar.Value = 0; this.Syn_Button.Enabled = this.Asyn_Button.Enabled = true; this.progressLabel.Visible = false; })); } private void sellButton_Click(object sender, EventArgs e) { number = 10; infoBox.Clear(); Thread[] ths = new Thread[15]; for (int i = 0; i < 15; i++) ths[i] = new Thread(sell); foreach (Thread th in ths) th.Start(); } private void sell() { //lock对象,对所有线程唯一 lock (lockObj) { if (number > 0) { Thread.Sleep(400); number--; this.BeginInvoke(new Action(() => { infoBox.AppendText("还剩" + number + "张飞机票!\n"); })); } } } //委托回调的方法 private void calculateButton_Click(object sender, EventArgs e) { int baseNumber = default(int); if(!int.TryParse(inputNumber.Text,out baseNumber)&&baseNumber<0) { MessageBox.Show("请输入一个非负整数!"); return; } resultBox.Clear(); IProgress<int> progressReporter = new Progress<int>((p) => { this.calculateBar.Value = p; }); Func<int, BigInteger> ComputeAction = new Func<int, BigInteger>((bsNum) => { BigInteger result =1; for (int i = 1; i <= bsNum; i++) { result *= i; progressReporter.Report((int)((double)i/(double)bsNum*100.0)); } return result; }); calculateButton.Enabled = false; ComputeAction.BeginInvoke(baseNumber, new AsyncCallback(getResult), ComputeAction); } //回调函数标准样例 private void getResult(IAsyncResult ar) { Func<int, BigInteger> func = ar.AsyncState as Func<int,BigInteger>; BigInteger rt = func.EndInvoke(ar); this.BeginInvoke(new Action(()=>{ this.resultBox.AppendText("计算结果:"+rt.ToString()); calculateButton.Enabled = true; })); } //并行计算的结果 private void taskBeginButton_Click(object sender, EventArgs e) { int base1, base2, base3; if(!int.TryParse(taskI.Text,out base1)) { MessageBox.Show("第一个任务数据输入错误!"); return; } if (!int.TryParse(taskII.Text, out base2)) { MessageBox.Show("第二个任务数据输入错误!"); return; } if (!int.TryParse(taskIII.Text, out base3)) { MessageBox.Show("第三个任务数据输入错误!"); return; } Action ac1 = new Action(() => { int sum = 0; for (int i = 0; i < base1; i++) sum += i; this.BeginInvoke(new Action(() => { taskIResult.Text = "任务一结果:"+sum.ToString(); })); }); Action ac2 = new Action(() => { int sum = 0; for (int i = 0; i < base2; i++) sum += i; this.BeginInvoke(new Action(() => { taskIIResult.Text = "任务二结果:" + sum.ToString(); })); }); Action ac3 = new Action(() => { int sum = 0; for (int i = 0; i < base3; i++) sum += i; this.BeginInvoke(new Action(() => { taskIIIResult.Text = "任务三结果:" + sum.ToString(); })); }); Parallel.Invoke(ac1,ac2,ac3); } private void BeginWriteFile_Click(object sender, EventArgs e) { int fileNum; long fileSize; if(string.IsNullOrWhiteSpace(filePath.Text)) { MessageBox.Show("请输入有效的目录名!"); return; } if(!int.TryParse(fileNumber.Text,out fileNum)) { MessageBox.Show("请输入有效的文件数量!"); return; } if (!long.TryParse(fileNumber.Text, out fileSize)) { MessageBox.Show("请输入有效的文件大小!"); return; } //清除文本显示 fileInfoBox.Clear(); //创建目录 if(!Directory.Exists(filePath.Text)) { Directory.CreateDirectory(filePath.Text); } //生成文件名 List<string> fileNames = new List<string>(); for(int i=0;i<fileNum;i++) { string tempStr = "File_" + i; fileNames.Add(System.IO.Path.Combine(System.IO.Path.GetFullPath(filePath.Text),tempStr)); } Random rand = new Random(); Action<string> action = new Action<string>( (string name) =>{ FileInfo fi = new FileInfo(name); if(fi.Exists) { fi.Delete(); } byte[] data=new byte[fileSize]; rand.NextBytes(data); using(FileStream fs=fi.Create()) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(data); bw.Close(); bw.Dispose(); fs.Clos 4000 e(); } this.BeginInvoke(new Action(() => { fileInfoBox.AppendText("文件" + name + "已经写入!\n"); })); }); //并行计算 Parallel.ForEach<string>(fileNames,action); } } }
相关文章推荐
- c#调用COM组件
- C#实现把指定数据写入串口
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#通用邮件发送类分享
- ruby实现的一个异步文件下载HttpServer实例
- C#中this的用法集锦
- C#.NET获取拨号连接的宽带连接方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#生成饼形图及添加文字说明实例代码
- C#判等对象是否相等的方法汇总
- C#简单的向量用法实例教程
- C#实现基于链表的内存记事本实例
- C#托管堆对象实例包含内容分析
- C#实现按照指定长度在数字前补0方法小结
- C# 通过 inline-asm 解决嵌入x86汇编
- C#虚方法的声明和使用实例教程