1 – Task
public async Task<List<Client>> GetAllAsync() { List<Client> clients = new List<Client>(); using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=SSPI;")) { await connection.OpenAsync(); using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT [Id],[Name],[Email],[CategoryId] FROM [dbo].[Client]"; using (SqlDataReader reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { Client client = new Client(); client.ClientID = reader["Id"] == DBNull.Value ? default(int) : int.Parse(reader["Id"].ToString()); client.ClientName = reader["Name"] == DBNull.Value ? default(string) : reader["Name"].ToString(); client.Email = reader["Email"] == DBNull.Value ? default(string) : reader["Email"].ToString(); client.CategoryID = reader["CategoryId"] == DBNull.Value ? default(int) : int.Parse(reader["CategoryId"].ToString()); clients.Add(client); } } } } return clients; } |
private async void button2_Click(object sender, EventArgs e) { IClientService<Client> clientService = new ClientService(); List<Client> clients= await clientService.GetAllAsync(); dataGridView1.DataSource = clients; } |
public class ClientService :IService { private SynchronizationContext synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();
public virtual bool GetAllAsync(Action<OperationResult<List<Client>>> callback) { // Le résultat comprenant l'objet ou l'erreur OperationResult<List<Client>> response = new OperationResult<List<Client>>();
WaitCallback waitCallBack = param => { try { response.Result = GetAll(); } catch(Exception ex) { response.Error = ex; } finally { synchronizationContext.Post(d => callback((OperationResult<List<Client>>)d), response); } }; return ThreadPool.QueueUserWorkItem(waitCallBack); }
public List<Client> GetAll() { List<Client> result = new List<Client>(); DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); using (DbConnection connection = factory.CreateConnection()) { connection.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=dbDemo;Integrated Security=SSPI;"; connection.Open();
using (DbCommand command = connection.CreateCommand()) { command.CommandText = "select TOP 1000 Id,Name,Email from [dbo].[Client]"; using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Client client = new Client(); client.ClientID = Convert.ToInt32(reader["Id"]); client.ClientFullName = reader["Name"].ToString(); client.Email = reader["Email"].ToString();
result.Add(client); } } } } return result; } } |
OperationResult(contenant soit le résultat soit l'erreur)
public interface IOperationResult { Exception Error { get; } } public interface IOperationResult<T> : IOperationResult { T Result { get; } } public class OperationResult : IOperationResult { public Exception Error { get; protected internal set; } } public class OperationResult<T> : OperationResult, IOperationResult<T> { public T Result { get; protected internal set; } } |
Client , une classe métier implémentant INotifyPropertyChanged
«Context »
public class Context :ObservedBase { private ObservableCollection<Client> _clients;
public ObservableCollection<Client> Clients { get { return _clients; } set { _clients = value; RaisePropertyChanged<ObservableCollection<Client>>(() => Clients); } } private IService service;
public Context() { this.service = new ClientService(); service.GetAllAsync(Callback); }
private void Callback(OperationResult<List<Client>> response) { Clients =new ObservableCollection<Client>(response.Result); } } |
Ou Méthode anonyme
public Context() { this.service = new ClientService(); service.GetAllAsync( (response) => { Clients =new ObservableCollection<Client>(response.Result); }); } |
Il suffit ensuite de définir le datacontext et binder les controls sur les propriétés de Clients
Task-based Asynchronous Pattern
await