如何实现支持异步方法的类?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何实现支持异步方法的类?相关的知识,希望对你有一定的参考价值。
我已经创建了一组类,负责获取数据并将其保存到源。我想为这些类添加异步功能但我在异步编程方面很弱,我不知道实现它的最佳方法是什么。我写了一个我正在尝试做的例子
如何以最佳方式实现异步方法?
这是Main类:
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库的替代解决方案,例如使用async 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,而无需编写所有样板代码。
https://dapper-tutorial.net/async
另一答案
实现方法的异步版本,如下所示:
public async Task LoadElementsAsync()
{
await Task.Factory.StartNew(LoadElements);
}
以上是关于如何实现支持异步方法的类?的主要内容,如果未能解决你的问题,请参考以下文章