Cycle de progression Faire (quelque chose qui marche) -> comprendre ce que l’on fait/comment cela marche -> pousser plus loin les notions
Il est conseillé de préférer l’utilisation des méthodes asynchrones pour des UI réactives.
| public async Task CreateAndWriteAsyncToFile() { using (FileStream stream = new FileStream("test.dat", FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) { byte[] data = new byte[100000]; new Random().NextBytes(data); await stream.WriteAsync(data, 0, data.Length); } } |
| private async void btWriteFile_Click(object sender, EventArgs e) { string response = await GetHttpClientStringAsync("http://www.microsoft.com"); } public async Task<string> GetHttpClientStringAsync(string path) { HttpClient client = new HttpClient(); return await client.GetStringAsync(path); } |
| public static void Main() { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; Task task = Task.Run(() => { while (!token.IsCancellationRequested) { Console.Write("*"); Thread.Sleep(1000); } // simule une erreur //token.ThrowIfCancellationRequested(); }, token); try { Console.WriteLine("Press enter to stop the task"); Console.ReadLine(); cancellationTokenSource.Cancel(); task.Wait(); } catch (AggregateException e) { Console.WriteLine(e.InnerExceptions[0].Message); } Console.WriteLine("Press enter to end the application"); Console.ReadLine(); } |
| public async Task ExecuteMultipleRequests() { HttpClient client = new HttpClient(); string microsoft = await client.GetStringAsync("http://www.microsoft.com"); string msdn = await client.GetStringAsync("http://msdn.microsoft.com"); string blogs = await client.GetStringAsync("http://blogs.msdn.com/"); //On pourrait afficher le résultat par exemple : rtb.AppendText(microsoft); } |
| public async Task ExecuteMultipleRequestsInParallel() { HttpClient client = new HttpClient(); Task microsoft = client.GetStringAsync("http://www.microsoft.com"); Task msdn = client.GetStringAsync("http://msdn.microsoft.com"); Task blogs = client.GetStringAsync("http://blogs.msdn.com/"); await Task.WhenAll(microsoft, msdn, blogs); } |
| private async void btReadData_Click(object sender, EventArgs e) { List<Client> clients = await GetAllClientsAsync(); dataGridView1.DataSource = clients; // mise à jour int result = await DeleteClientAsync(1978); } public async Task<List<Client>> GetAllClientsAsync() { List<Client> result = new List<Client>(); using (DbConnection connection = GetConnection()) { using (DbCommand command = connection.CreateCommand()) { command.CommandText = "SELECT [Id],[Name],[Email] FROM [dbo].[Client]"; await connection.OpenAsync(); using (DbDataReader 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(); result.Add(client); } } } } return result; } public async Task<int> DeleteClientAsync(int id) { int result = 0; using (DbConnection connection = GetConnection()) { using (DbCommand command = connection.CreateCommand()) { command.CommandText = "Delete from [dbo].[Client] where id=@id"; command.Parameters.Add(CreateParameter(command, "@id",id)); await connection.OpenAsync(); result = await command.ExecuteNonQueryAsync(); } } return result; } // Méthodes d'aide public DbConnection GetConnection() { ConnectionStringSettings csSection = ConfigurationManager.ConnectionStrings["defaultConnectionString"]; DbConnection connection = DbProviderFactories.GetFactory(csSection.ProviderName).CreateConnection(); connection.ConnectionString = csSection.ConnectionString; return connection; } public DbParameter CreateParameter(DbCommand command, string parameterName, object value) { DbParameter parameter = command.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; return parameter; } |
| public static class DbCommandExtensions { public static DbParameter CreateParameter(this DbCommand command, string parameterName, object value) { DbParameter parameter = command.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; return parameter; } } |