在第
引言
在線程池中有固定不變的大量線程可用於服務請求
背景
在第
public abstract class DataSourceView {
public virtual void Select(DataSourceSelectArguments arguments
DataSourceViewSelectCallback callback);
protected abstract IEnumerable ExecuteSelect(
DataSourceSelectArguments arguments);
}
您會注意到
那些熟悉框架中的異步 API 的人會注意到缺少了異步模式
關於異步任務
框架
在此框架中(在此系列結尾會用示例的剩余部分來演示這一點)
public abstract class AsyncDataSourceControl : DataSourceControl
IAsyncDataSource {
private bool _performAsyncDataAccess;
protected AsyncDataSourceControl() {
_performAsyncDataAccess = true;
}
public virtual bool PerformAsyncDataAccess {
get; set;
}
bool IAsyncDataSource
get { return _performAsyncDataAccess && Page
}
}
public abstract class AsyncDataSourceView : DataSourceView {
protected abstract IAsyncResult BeginExecuteSelect(
DataSourceSelectArguments arguments
AsyncCallback asyncCallback
object asyncState);
protected abstract IEnumerable EndExecuteSelect(
IAsyncResult asyncResult);
protected override IEnumerable ExecuteSelect(
DataSourceSelectArguments arguments) {
//實現從 DataSourceView 中繼承的
//抽象 ExecuteSelect 方法
//方法是使用 BeginExecuteSelect 和 EndExecuteSelect
//以便通過阻止來
//進行同步數據訪問
}
private IAsyncResult OnBeginSelect(object sender
EventArgs e
object extraData);
private void OnEndSelect(IAsyncResult asyncResult);
public override void Select(DataSourceSelectArguments arguments
DataSourceViewSelectCallback callback) {
if (_owner
//使用 OnBeginSelect 和 OnEndSelect
//作為 BeginEventHandler 和 EndEventHandler 方法
//來調用 Page
//以指明需要
//進行異步工作
//調用特定的
//數據源實現
//已在此類中引入的
//抽象 BeginExecuteSelect 和 EndExecuteSelect
//方法
}
else {
//執行同步數據訪問
base
}
}
}
示例
現在
public class AsyncWeatherDataSource : AsyncDataSourceControl {
//與 WeatherDataSource 相同
}
private sealed class AsyncWeatherDataSourceView : AsyncDataSourceView {
private AsyncWeatherDataSource _owner;
private WeatherService _weatherService;
public AsyncWeatherDataSourceView(AsyncWeatherDataSource owner
string viewName)
: base(owner
_owner = owner;
}
protected override IAsyncResult BeginExecuteSelect(DataSourceSelectArguments arguments
AsyncCallback asyncCallback
object asyncState) {
arguments
string zipCode = _owner
if (zipCode
return new SynchronousAsyncSelectResult(/* selectResult */
null
asyncCallback
}
_weatherService = new WeatherService(zipCode);
return _weatherService
}
protected override IEnumerable EndExecuteSelect(IAsyncResult asyncResult) {
SynchronousAsyncSelectResult syncResult =
asyncResult as SynchronousAsyncSelectResult;
if (syncResult != null) {
return syncResult
}
else {
Weather weatherObject =
_weatherService
_weatherService = null;
if (weatherObject != null) {
return new Weather[] { weatherObject };
}
}
return null;
}
}
要注意的關鍵問題是
對於那些實際缺少異步模式的框架
最有趣的可能是 SynchronousAsyncSelectResult 類(在某種程度上而言是一種矛盾)
頁面基礎結構隱藏了在 Microsoft 上下文中執行異步工作的大部分詳細信息
From:http://tw.wingwit.com/Article/program/net/201311/13019.html