Bla*_*_99 0 c# mutex asynchronous httpclient async-await
I am trying to get the response from a url, and when I use the await and async in my function, my Mutex throws an error.
Error output :
System.ApplicationException
Object synchronization method was called from an unsynchronized block of code.
at System.Threading.Mutex.ReleaseMutex()
Run Code Online (Sandbox Code Playgroud)
Code :
private async void getData ()
{
_mutex.WaitOne();
try
{
string url = "https://urllink.com";
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
}
catch (Exception e)
{
// TODO
throw e;
}
_mutex.ReleaseMutex();
}
Run Code Online (Sandbox Code Playgroud)
I would propose two three changes here:
async void with async Task (credit: Fildor), and make sure you await itMutex with SemaphoreSlim (a new SemaphoreSlim(1,1) is basically the same thing as a Mutex) - the Mutex documentation is heavily focused on "the thread that owns the mutex", which strongly suggests it is thread-bound, and await is incompatible with thread-bound scenarios; SemaphoreSlim, however, is not thread-bound; additionally, it has an async-aware WaitAsync() API, avoiding thread blocks (i.e. replace _mutex.WaitOne(); with await _semaphore.WaitAsync();)finally, so that it is released even in the failure caseBut "1" seems to be the real problem here. I would also speculate that this code worked fine until it was changed to async.
您也可以删除catch, 因为catch刚刚拥有的 athrow是多余的;一catch,仅仅有throw e;是雪上加霜不是多余的:它打破了堆栈跟踪。
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |