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

C#异步使用

2012-12-13 16:54 141 查看
突然想到很久没有用到异步了,所以花了一个下午的时间重新复习一下,写的比较简单,如果是大牛或者想批评的请绕行,我只是想给初学者和自己留个记录好以后看

我的业务思路是这样的:

前台接电话

接电话的同时她得拿笔记录客户的信息吧

那这种一边接电话一边记录就是异步咯

还有接完电话,他得把客户信息交给服务员,让他去招呼客户

这个就是异步回调咯

废话不说 直接贴代码,每句话我都有注释了,不懂可以留言,我有上博客园就一定回

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;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace Background
{
//声明一个接电话的委托
public delegate string CallPeoleDelegate();
//声明一个接完电话的委托
public delegate void MessageDelegate(string message);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//接电话按钮
private void button1_Click(object sender, EventArgs e)
{
//接客
this.textBox1.AppendText("接客\r\n");
//接电话
CallPeoleDelegate p = new CallPeoleDelegate(Call);
//接电话中..
IAsyncResult ar = p.BeginInvoke(CallPeople, null);
//记录客人信息
Writer();
//是否接电话完成
bool flag = true;
while (flag)
{
//没完成,继续
this.textBox1.AppendText(string.Format("正在咨询其他问题...\r\n"));
//模拟正在接电话,每1秒一次
flag = !ar.AsyncWaitHandle.WaitOne(1000);
}
}
//把信息显示到文本框
void showmessage(string message)
{
this.textBox1.AppendText(message);
}
//接电话
public string Call()
{
Thread.Sleep(3000);
return "电话接完,已经交给服务员";
}
//记录
public void Writer()
{
this.textBox1.Text += "客户名称:小明\r\n电话12312324234\r\n";
}

//把客户信息提交给服务员
public void CallPeople(IAsyncResult ar)
{
//实例化接完电话委托
MessageDelegate m = new MessageDelegate(showmessage);
//声明异步回调对象
AsyncResult result = (AsyncResult)ar;
//获取异步回调对象
CallPeoleDelegate pd = (CallPeoleDelegate)result.AsyncDelegate;
//得到Call方法返回值
string message = pd.EndInvoke(ar);
//判断线程是否同步
if (this.InvokeRequired)
{
//同步,调用接完电话方法,并把返回值传递进去
this.Invoke(m, message);
}
}

}
}

Dome在这里http://files.cnblogs.com/linyijia/%E5%BC%82%E6%AD%A5%E5%9B%9E%E8%B0%83.rar

有点累了,就写到这里吧 里面还是有些不足的,以后有时间再补上去
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: