【问题标题】:Task<T> queueing任务<T> 排队
【发布时间】:2016-10-19 06:07:43
【问题描述】:

我有以下方法

public async Task<T> SomeMethod(parameters)
{
    // here we execute some instructions which are not thread safe
}

我需要 SomeMethod 来返回一个 Task,以便其他方法可以异步运行(等待)它,而不会阻塞 UI 线程。

问题是 SomeMethod 可以并行调用,因为执行返回到 UI 线程,这会引发异常,因为 SomeMethod() 中的某些调用不是线程安全的。

确保对 SomeMethod 的所有调用都排队(并且可以等待)并且该队列将按顺序执行的最佳方法是什么?

【问题讨论】:

标签: c# multithreading thread-safety async-await


【解决方案1】:

使用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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多