异步编程
异步编程的三种模式
TAP模式(Task-based Asynchronous Pattern)
tsak 异步编程使用
- 当程序中有大量I/O操作(如:读写数据库、上传或下载数据、读取或写入文件)等操作时,可以考虑使用异步
- 当程序中耗时的操作时,可以使用task.run()方式,在后台线程中调用耗时方法。
APM模式(Asynchronous-Programming-Model)
- 当委托对象调用时,它调用了它的调用列表中包含的方法。就像程序调用方法一样,这是同步完成的。
- 如果委托对象在调用列表中只有一个方法(可以叫做引用方法),通过调用BeginInvoke和EndInvoke可以异步执行这个方法。
- 当调用委托的BeginInvoke方法时,它开始在一个独立线程上执行引用方法,并且立即返回到原始线程。原始线程可以继续,而引用方法会在线程池的线程中执行。
APM 三种模式
No matter which technique you use, always call EndInvoke to complete your asynchronous call.
无论使用那种方式,都会调用EndInvoke 来结束异步调用。
1. 阻塞模式
(EndInvoke )阻塞模式
调用EndInvoke 方法,EndInvoke 可能会阻塞调用线程,直到异步方法返回。因为EndInvoke 是阻塞模式,所以在界面主线程,例如winform 主线程不要使用这种方式。
示例代码:
using System;
using System.Net.Sockets;
using System.Threading;
using static ConsoleApp1.AsyncDemo;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Because EndInvoke might block, you should never call it from threads that service the user interface.
int threadId;
AsyncDemo ad = new AsyncDemo();
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
//异步调用:BeginInvoke
IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
Console.WriteLine("main threadID:{0} dose some work.", Thread.CurrentThread.ManagedThreadId);
//调用EndInvoke 等待异步调用完成,并获取返回结果。
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine($"the call executed on threadID: {threadId} ,with return value\"{returnValue}\".");
Console.ReadKey();
}
}
public class AsyncDemo
{
The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadID)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadID = Thread.CurrentThread.ManagedThreadId;
return $"My call time was {callDuration}.";
}
// The delegate must have the same signature as the method ,it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
}
(WaitHandle )阻塞模式
使用IAsyncResult 的AsyncWaitHandle 属性,当异步调用完成时 会通知WaitHandle 。
需要注意的是:当调用EndInvoke时, WaitHandle不是自动关闭的。在使用完WaitHandle 时,需调用
WaitHandle.Close方法,释放系统资源。
示例代码:
using System;
using System.Net.Sockets;
using System.Threading;
using static ConsoleApp1.AsyncDemo;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int threadId;
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
//异步调用:BeginInvoke
IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
Console.WriteLine("main threadID:{0} dose some work.", Thread.CurrentThread.ManagedThreadId);
//等待WaitHandle被通知
result.AsyncWaitHandle.WaitOne();
//调用EndInvoke 获取返回结果。
string returnValue = caller.EndInvoke(out threadId, result);
//释放WaitHandle
result.AsyncWaitHandle.Close();
Console.WriteLine($"the call executed on threadID: {threadId} ,with return value\"{returnValue}\".");
Console.ReadKey();
}
}
public class AsyncDemo
{
The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadID)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadID = Thread.CurrentThread.ManagedThreadId;
return $"My call time was {callDuration}.";
}
// The delegate must have the same signature as the method ,it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
}
2.轮询模式
- 使用轮询模式
监控IAsyncResult. IsCompleted 属性,判断异步调用是否完成。在界面主线程中,也可以使用这种方式。
轮询模式,当异步调用仍在运行时,允许调用线程继续执行相关操作
示例代码:
using System;
using System.Net.Sockets;
using System.Threading;
using static ConsoleApp1.AsyncDemo;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int threadId;
// Create an instance of the test class
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
//异步调用:BeginInvoke
IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
Console.WriteLine("main threadID:{0} dose some work.", Thread.CurrentThread.ManagedThreadId);
// Poll while simulating work.
while (result.IsCompleted == false)
{
//主线程继续其他操作
Thread.Sleep(250);
Console.Write(".");
}
Console.WriteLine();
//调用EndInvoke 获取返回结果。
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine($"the call executed on threadID: {threadId} ,with return value\"{returnValue}\".");
Console.ReadKey();
}
}
public class AsyncDemo
{
The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadID)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadID = Thread.CurrentThread.ManagedThreadId;
return $"My call time was {callDuration}.";
}
// The delegate must have the same signature as the method ,it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
}
3. 回调模式
-
使用回调模式
-
在回调模式中,原始线程一直执行,无需等待或检查发起的线程是否完成。
在发起的线程中的引用方法完成后,发起的线程就会调用回调方法,由回调方法调用EndInvoke 处理异步方法的结果。
BeginInvoke的参数列表中的最后两个参数:
第一参数callback,是回调方法的名字
第二参数 state ,可以是null,或是要传入回调方法的一个对象的引用。
可以通过使用IAsyncResult参数的AsyncState属性来获取这个对象,参数类型是object
- 回调方法是在ThreadPool thread 上运行的。线程池中的线程是后台线程,当主程序退出时,后台线程也会退出,
所以,主线程调用sleep()来等待,回调方法执行结束。
示例代码:
using System;
using System.Net.Sockets;
using System.Threading;
using static ConsoleApp1.AsyncDemo;
using System.Runtime.Remoting.Messaging;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Create an instance of the test class
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
int dummy = 0;
//异步调用:BeginInvoke
IAsyncResult result = caller.BeginInvoke(3000, out dummy,
new AsyncCallback(CallbackMethod), "the call executed on thread:{0} ,with return value \"{1}\".");
Console.WriteLine("main threadID:{0} continues to execute......", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);///等待异步回调完成。
Console.WriteLine("mian thread ends");
Console.ReadKey();
}
/// <summary>
/// 回调方法
/// </summary>
/// <param name="ar"></param>
static void CallbackMethod(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult)ar;
AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;
// Retrieve the format string that was passed as state
// information.
string formatSting = (string)ar.AsyncState;
int threadId = 0;
//调用EndInvoke 获取返回结果。
string returnValue = caller.EndInvoke(out threadId, ar);
Console.WriteLine(formatSting, threadId, returnValue);
Console.WriteLine("callback method---current threadId:{0}", Thread.CurrentThread.ManagedThreadId);
}
}
public class AsyncDemo
{
The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadID)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadID = Thread.CurrentThread.ManagedThreadId;
return $"My call time was {callDuration}.";
}
// The delegate must have the same signature as the method ,it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
}
//输出结果:
/*
main threadID:1 continues to execute......
Test method begins.
the call executed on thread:3 ,with return value "My call time was 3000.".
callback method---current threadId:3
mian thread ends
*/
从输出结果:可以看到回调方法与异步方式使用的同一个线程(ThreadPool thread )
- EndInvoke方法用来获取由异步方法返回的值,并且释放线程使用的资源。EndInvoke有如下特性
- 它有一个由BeginInvoke方法返回的IAsyncResult的参数。
- 如果线程池已经退出,EndInvoke清理退出线程的状态并且释放其资源;它找到引用方法返回值并且把它作为返回值
- 如果当EndInvoke被调用时线程池中的线程仍在运行,调用线程会停止并等待,直到清理完毕并返回值。因为EndInvoke是为开启的线程进行清理,所以必须保证确保对每一个BeginInvoke调用EndInvoke。
- 如果异步方法触发了异常,在调用EndInvoke时会抛出异常。
更多关于回调模式的使用可以参考另一篇文章
回调模式