Hi @Farshad Valizade , Welcome to Microsoft Q&A,
It should be noted that ADO.NET itself does not support asynchronous operations of SqlConnection or SqlCommand. To achieve asynchronous behavior, you may consider using the "Task.Run" method to offload synchronous operations to a separate thread.
- Added
Async
suffix toGetAllAsync
method. - Use "OpenAsync" and "ExecuteReaderAsync" in the DAL for asynchronous operations.
- Change the BLL method to return a
Task<DataTable>
and wait for the DAL method. - Modify UI methods to use
await
when calling BLL methods.
Remember, if you use "await" in a UI method, you need to mark it as "async". Also, be aware of potential issues with UI thread synchronization when updating the UI from an asynchronous operation.
Dal:
public static async Task<DataTable> GetAllAsync()
{
using DataTable dt = new DataTable();
try
{
string query = "SELECT * From Documents";
using SqlCommand cmd = new SqlCommand(query, Connection.Conn);
await Connection.OpenAsync(); // Use OpenAsync for asynchronous opening
using SqlDataReader rd = await cmd.ExecuteReaderAsync();
await Task.Run(() => dt.Load(rd)); // Offload synchronous operation to a separate thread
}
catch (Exception ex)
{
Error = ex.Message;
}
finally
{
Connection.Close();
}
return dt;
}
BLL:
public static async Task<DataTable> GetAllAsync()
{
return await DocumentDAL.GetAllAsync();
}
UI:
private async void btnLoad_Click(object sender, EventArgs e)
{
Datagridview1.DataSource = await DocumentBLL.GetAllAsync();
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.