[英]How to implement a class that support async methods?
我已經創建了一組類,這些類將負責獲取數據並將其保存到源中。 並且我想向這些類添加異步功能,但是我在異步編程方面很弱,我不知道實現它的最佳方法是什么。 我寫了一個我想做的事的例子
如何以最佳方式實現異步方法?
這是主類:
public sealed class SourceManager : IDisposable
{
public SourceManager(string connectionString)
{
ConnectionString = connectionString;
MainDataSet = new DataSet();
Elements = new List<SourceElement>();
// this is for example
Elements.Add(new SourceElement(this, "Table1"));
Elements.Add(new SourceElement(this, "Table2"));
Elements.Add(new SourceElement(this, "Table3"));
Elements.Add(new SourceElement(this, "Table4"));
}
public void Dispose()
{
MainDataSet?.Dispose();
Elements?.ForEach(element => element.Dispose());
}
public DataSet MainDataSet { get; }
public string ConnectionString { get; }
public List<SourceElement> Elements { get; }
public void LoadElements()
{
Elements.ForEach(element => element.Load());
}
public Task LoadElementsAsync()
{
throw new NotImplementedException();
}
public void UpdateAll()
{
Elements.ForEach(element => element.Update());
}
public void UpdateAllAsync()
{
throw new NotImplementedException();
}
}
這是元素類:
public sealed class SourceElement : IDisposable
{
private readonly SqlDataAdapter _adapter;
public SourceElement(SourceManager parentManager, string tableName)
{
ParentManager = parentManager;
TableName = tableName;
_adapter = new SqlDataAdapter($"SELECT * FROM [{TableName}];",
ParentManager.ConnectionString);
_adapter.FillSchema(ParentManager.MainDataSet, SchemaType.Mapped,
TableName);
}
public void Dispose()
{
_adapter?.Dispose();
}
public string TableName { get; }
private SourceManager ParentManager { get; }
public void Load()
{
_adapter.Fill(ParentManager.MainDataSet, TableName);
}
public Task LoadAsync()
{
throw new NotImplementedException();
}
public void Update()
{
_adapter.Update(ParentManager.MainDataSet.Tables[TableName]);
}
public Task UpdateAsync()
{
throw new NotImplementedException();
}
}
這就是我的使用方式
public partial class Form1 : Form
{
private SourceManager sourceManager;
public Form1()
{
InitializeComponent();
// here we initialize the sourceManager cuz we need its elements
on draw the controls in the form
sourceManager = new
SourceManager("Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;");
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// here I want to fill the data tables without interrupting the interface
// I need to show a progress
sourceManager.LoadElementsAsync();
}
public void SaveAll()
{
// Here I I want to save the data without interrupting the interface thread
sourceManager.UpdateAllAsync();
}
public void SaveData(string tableName)
{
// Here I I want to save the data without interrupting the interface thread
sourceManager.Elements.Find(element => element.TableName.Equals(tableName))?.UpdateAsync();
}
}
SqlDataAdapter沒有異步方法。 您將必須自己實施它,我不建議這樣做。
樣品
await Task.Run(() =>_adapter.Fill(ParentManager.MainDataSet, TableName));
但是我將研究使用其他ADO.NET庫的替代解決方案,例如使用異步SqlDataReader 。
樣品
public async Task SomeAsyncMethod()
{
using (var connection = new SqlConnection("YOUR CONNECTION STRING"))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = "YOUR QUERY";
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
// read from reader
}
}
}
}
查看.NET Framework 4.5中添加的異步編程功能部分
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming
但是我什至都不會理會這些,而只是使用Dapper即可支持異步方法,而無需編寫所有樣板代碼。
像這樣實現方法的異步版本:
public async Task LoadElementsAsync()
{
await Task.Factory.StartNew(LoadElements);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.