SemaphoreSlim and async/await

独自空忆成欢 提交于 2019-12-13 21:48:45

问题


This works:

int _counter;
readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

async void Button_Click(object sender, RoutedEventArgs e)
{
    if (_semaphore.Wait(0))
    {
        Title = $"{ ++_counter}";
        await Task.Delay(1000); // simulate work
        Title = $"{ --_counter}";
        _semaphore.Release();
    }
}

After first click further buttons clicks are ignored until work is finished. Tittle can be 1 or 0.

And this doesn't work

void Button_Click(object sender, RoutedEventArgs e)
{
    if (_semaphore.Wait(0))
    {
        Test(); // moving code into separate method
        _semaphore.Release();
    }
}

async void Test()
{
    Title = $"{ ++_counter}";
    await Task.Delay(1000); // simulate work
    Title = $"{ --_counter}";
}

Clicking button continuously will rise Tittle to 2, 3, and so on.

What am I doing wrong?


回答1:


async void only makes sense in event handlers. It is a special type of asynchronism. It means "fire and forget".

You don't want to fire and forget the Test() method. You want to wait for it to return.

Change your Test signature to:

// Note that it returns a "Task". A task is an awaitable promise.
async Task Test()
{
   //...
}

And then await it on your event handler:

async void Button_Click(object sender, RoutedEventArgs e)
{
     if (_semaphore.Wait(0))
     {
        await Test(); // moving code into separate method
        _semaphore.Release();
    }
}


来源:https://stackoverflow.com/questions/40239795/semaphoreslim-and-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!