您的位置:首页 > 编程语言 > C#

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#