public class PrimeFactorizer
{
public bool Factorize(int factorizableNum, ref int primefactor1, ref int primefactor2)
{
// Determine whether factorizableNum is prime.
// If it is prime, return true. Otherwise, return false.
// If it is prime, place factors in primefactor1 and primefactor2.
}
}
如果遵循异步模式,则类库编写器添加 BeginFactorize 和 EndFactorize 方法,这两个方法将同步操作拆分成两个异步操作:
public class PrimeFactorizer
{
public bool Factorize(
int factorizableNum,
ref int primefactor1,
ref int primefactor2)
{
// Determine whether factorizableNum is prime.
// if it is prime, return true; otherwise return false.
// if it is prime, place factors in primefactor1 and primefactor2
}
public IAsyncResult BeginFactorize(
int factorizableNum,
ref int primefactor1,
ref int primefactor2,
AsyncCallback callback,
Object state)
{
// Begin factoring asynchronously, and return a result object,
}
public bool EndFactorize(
ref int primefactor1,
ref int primefactor2,
IAsyncResult asyncResult
)
{
// End (or complete) the factorizing,
// return the results,
// and obtain the prime factors.
}
}
服务器将异步操作拆分成两个逻辑部分:采用来自客户端的输入并调用异步操作的部分,向客户端提供异步操作结果的部分。
在开始异步调用时提供回调委托。
public class Driver1
{
public PrimeFactorizer primeFactorizer;
public void Results(IAsyncResult asyncResult)
{
int primefactor1=0;
int primefactor2=0;
bool prime = primeFactorizer.EndFactorize(
ref primefactor1,
ref primefactor2,
asyncResult);
}
public void Work()
{
int factorizableNum=1000589023,
int primefactor1=0;
int primefactor2=0;
Object state = new Object();
primeFactorizer = new PrimeFactorizer();
AsyncCallback callback = new Callback(this.Results);
IAsyncResult asyncResult = primeFactorizer.BeginFactorize(
factorizableNum,
ref primefactor1,
ref primefactor2,
callback,
state);
}
}
在开始异步调用时不提供回调委托。
public class Driver2
{
public static void Work()
{
int factorizableNum=1000589023,
int primefactor1=0;
int primefactor2=0;
Object state = new Object();