异步编程模型
Begin/End模式
1,委托
在执行委托方法的时候,我们常常会看到一个Invoke,同时也有一对你或许不常使用的BeginInvoke,EndInvoke方法对,当然Invoke方法是阻塞主线程,而BeginInvoke则是另开一个线程。
2,流
在Stream抽象类中提供了这样两对BeginRead/EndRead,BeginWrite/EndWrite(异步读写)的方法,这样它的n多继承类都可以
实现异步读写
static void Main(string[] args)
{
var path = "D://1.txt";
FileStream fs = new FileStream(path, FileMode.Open);
FileInfo info = new FileInfo(path);
byte[] b = new byte[info.Length];
var asycState = fs.BeginRead(b, 0, b.Length, (result) =>
{
var file = result.AsyncState as FileStream;
Console.WriteLine("文件内容:{0}", Encoding.Default.GetString(b));
file.Close();
}, fs);
Console.WriteLine("我是主线程,我不会被阻塞!");
Console.ReadKey();
}
用Task包装一下
Task.Factory.FromAsync(fs.BeginRead, fs.EndRead, b, 0, b.Length, null, TaskCreationOptions.None).ContinueWith
(i =>
{
Console.WriteLine("文件内容:{0}", Encoding.Default.GetString(b));
});
事件模式
这个模式常以XXXCompleted的形式结尾