[英]How to implement a class that support async methods?
I already created group of classes that will be responsible about getting the data and saving it to the source. 我已经创建了一组类,这些类将负责获取数据并将其保存到源中。 and I want to add async capabilities to these classes but I weak at async programming and I don't know what is the best way to implement it.
并且我想向这些类添加异步功能,但是我在异步编程方面很弱,我不知道实现它的最佳方法是什么。 I wrote an example of what I'm trying to do
我写了一个我想做的事的例子
How to implement the async methods in the best way ? 如何以最佳方式实现异步方法?
this is the Main class: 这是主类:
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();
}
}
this is the element class : 这是元素类:
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();
}
}
and this is how I use it 这就是我的使用方式
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 does not have asynchronous methods. SqlDataAdapter没有异步方法。 You will have to implement it yourself which I don't recommend.
您将必须自己实施它,我不建议这样做。
sample 样品
await Task.Run(() =>_adapter.Fill(ParentManager.MainDataSet, TableName));
But I would look into an alternative solution using other ADO.NET libraries like using an async SqlDataReader . 但是我将研究使用其他ADO.NET库的替代解决方案,例如使用异步SqlDataReader 。
sample 样品
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
}
}
}
}
Look at section Asynchronous Programming Features Added in .NET Framework 4.5 查看.NET Framework 4.5中添加的异步编程功能部分
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming
But I would probably not even bother with any of this and just use Dapper which has support for async methods without you having to write all the boilerplate code. 但是我什至都不会理会这些,而只是使用Dapper即可支持异步方法,而无需编写所有样板代码。
https://dapper-tutorial.net/async https://dapper-tutorial.net/async
Implement the async versions of your methods like this: 像这样实现方法的异步版本:
public async Task LoadElementsAsync()
{
await Task.Factory.StartNew(LoadElements);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.