简体   繁体   中英

How to cancel Ado.Net async calls?

I have a function to query database

private async Task<IEnumerable<T>)> RunQuery<T>(string sql)
{
    using (var conn = new SqlConnection(_connStr))
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 300;
        await conn.OpenAsync().ConfigureAwait(false);
        var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
        // ... yield return the result from the reader

Some queries take a long time to run and I need to enable it to be cancelable (so it will release the database locks, etc). How to implement it?

As mentioned in the comments on the question, use the overload that takes a CancellationToken , as you can then trigger cancellation of the request via the CancellationTokenSource used to generate the token.

Simulating a long running task by dropping the following code into a Windows Forms app, shows this at work:

CancellationTokenSource _cts = new CancellationTokenSource();
bool _started = false;

private async void button1_Click(object sender, EventArgs e)
{
    if (!_started)
    {
        _started = true;
        using (var conn = new SqlConnection(_connStr))
        using (var cmd = new SqlCommand("WAITFOR DELAY '00:00:30'", conn))
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandTimeout = 300;
            await conn.OpenAsync().ConfigureAwait(false);
            var reader = await cmd.ExecuteReaderAsync(_cts.Token).ConfigureAwait(false);

            MessageBox.Show("Done");
        }
    }
    else
    {
        _cts.Cancel();
    }
}

Clicking the button on the form once triggers the request to the database and a second time requests that it be cancelled. This does cause an exception to be thrown which then needs to be handled appropriately:

取消数据库请求引发的异常

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM