我有以下方法
public async Task<T> SomeMethod(parameters)
{
// here we execute some instructions which are not thread safe
}
我需要SomeMethod来返回一个Task,这样其他方法就可以异步运行(等待)它,而不是阻塞UI线程。
问题是SomeMethod可以并行调用,因为执行会返回到UI线程,这会引发异常,因为SomeMethod()中的一些调用不是线程安全的。
确保对SomeMethod的所有调用都排队(并且等待)的最佳方法是什么,并且该队列将按顺序执行?
答案 0 :(得分:2)
使用AsyncLock阻止两个线程执行单个代码块:
(传统的lock
无法使用,因为您无法在其中使用await
关键字)
private AsyncLock myAsyncLock = new AsyncLock();
public async Task<T> SomeMethod(parameters)
{
using (await myAsyncLock.LockAsync())
{
// here we execute some instructions which are not thread safe
}
}
public class AsyncLock
{
private readonly AsyncSemaphore m_semaphore;
private readonly Task<Releaser> m_releaser;
public AsyncLock()
{
m_semaphore = new AsyncSemaphore(1);
m_releaser = Task.FromResult(new Releaser(this));
}
public Task<Releaser> LockAsync()
{
var wait = m_semaphore.WaitAsync();
return wait.IsCompleted ?
m_releaser :
wait.ContinueWith((_, state) => new Releaser((AsyncLock)state),
this, System.Threading.CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public struct Releaser : IDisposable
{
private readonly AsyncLock m_toRelease;
internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }
public void Dispose()
{
if (m_toRelease != null)
m_toRelease.m_semaphore.Release();
}
}
}
// http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx
public class AsyncSemaphore
{
private readonly static Task s_completed = Task.FromResult(true);
private readonly Queue<TaskCompletionSource<bool>> m_waiters = new Queue<TaskCompletionSource<bool>>();
private int m_currentCount;
public AsyncSemaphore(int initialCount)
{
if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount");
m_currentCount = initialCount;
}
public Task WaitAsync()
{
lock (m_waiters)
{
if (m_currentCount > 0)
{
--m_currentCount;
return s_completed;
}
else
{
var waiter = new TaskCompletionSource<bool>();
m_waiters.Enqueue(waiter);
return waiter.Task;
}
}
}
public void Release()
{
TaskCompletionSource<bool> toRelease = null;
lock (m_waiters)
{
if (m_waiters.Count > 0)
toRelease = m_waiters.Dequeue();
else
++m_currentCount;
}
if (toRelease != null)
toRelease.SetResult(true);
}
}