我正在實現一個異步服務。在評估微軟的example之後,我想知道他們的方法是否真的是異步的。我很確定它是這樣的,但是我在網上看到的一些樣本和參數AsyncCallback
引起我的疑惑。真正異步的WCF服務
根據實例,我們需要實現開始和末方法對這樣的:
public IAsyncResult BeginGetAcmeAnvil(AsyncCallback callback, object state)
{
// Starts synchronous task
var acmeAsyncResult = new AcmeAsyncResult<Anvil>
{
Data = new Anvil()
};
return acmeAsyncResult;
}
public Anvil EndGetAcmeAnvil(IAsyncResult result)
{
var acmeAsyncResult = result as AcmeAsyncResult<Anvil>;
return acmeAsyncResult != null
? acmeAsyncResult.Data
: new Anvil();
}
很簡單,但爲什麼我們有一個AsyncCallback
參數?我們是不是應該撥打電話callback
,這又會觸發End方法?
這是我的想法:
public delegate void AsyncMethodCaller(AcmeAsyncResult<Anvil> acmeAsyncResult,
AsyncCallback callback);
public IAsyncResult BeginGetAcmeAnvil(AsyncCallback callback, object state)
{
var acmeAsyncResult = new AcmeAsyncResult<Anvil>();
var asyncMethodCaller = new AsyncMethodCaller(GetAnvilAsync);
// Starts asynchronous task
asyncMethodCaller.BeginInvoke(acmeAsyncResult, callback, null, null);
return acmeAsyncResult;
}
private void GetAcmeAnvilAsync(AcmeAsyncResult<Anvil> acmeAsyncResult,
AsyncCallback callback)
{
acmeAsyncResult.Data = new Anvil();
callback(acmeAsyncResult); // Triggers EndGetAcmeAnvil
}
public Anvil EndGetAcmeAnvil(IAsyncResult result)
{
var acmeAsyncResult = result as AcmeAsyncResult<Anvil>;
return acmeAsyncResult != null
? acmeAsyncResult.Data
: new Anvil();
}
我沒有使用loadUI一些負載測試,但沒有明顯的性能變化。