MySQL Connector/NET Developer Guide

5.8 Asynchronous Methods

The Task-based Asynchronous Pattern (TAP) is a pattern for asynchrony in the .NET Framework. It is based on the Task and Task<TResult> types in the System.Threading.Tasks namespace, which are used to represent arbitrary asynchronous operations.

Async-Await are new keywords introduced to work with the TAP. The Async modifier is used to specify that a method, lambda expression, or anonymous method is asynchronous. The Await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes.



The following methods can be used with either TAP or Async-Await.

In addition to the methods listed above, the following are methods inherited from the .NET Framework:


The following examples demonstrate how to use the asynchronous methods:

In this example, a method has the async modifier because the method await call made applies to the method LoadAsync. The method returns a Task object that contains information about the result of the awaited method. Returning Task is like having a void method, but you should not use async void if your method is not a top-level access method like an event.

public async Task BulkLoadAsync()
  MySqlConnection myConn = new MySqlConnection("MyConnectionString");
  MySqlBulkLoader loader = new MySqlBulkLoader(myConn);

  loader.TableName       = "BulkLoadTest";
  loader.FileName        = @"c:\MyPath\MyFile.txt";
  loader.Timeout         = 0;

  var result             = await loader.LoadAsync();

In this example, an "async void" method is used with "await" for the ExecuteNonQueryAsync method, to correspond to the onclick event of a button. This is why the method does not return a Task.

private async void myButton_Click()
  MySqlConnection myConn = new MySqlConnection("MyConnectionString");
  MySqlCommand proc      = new MySqlCommand("MyAsyncSpTest", myConn);

  proc.CommandType       = CommandType.StoredProcedure;

  int result             = await proc.ExecuteNonQueryAsync();