C#中的同步任务执行

Gul*_*han 1 c# task-parallel-library async-await c#-4.0

我在Singleton类中有一个方法,它将从不同的线程调用.但我需要逐个执行它们.喜欢

将从多个线程调用ImageUtil.Instance.LoadImage(imageID)方法.但我想逐个加载图片.因此,一次只能加载一个图像.

public class ImageUtil
{
    #region Singleton Implementation
    private ImageUtil()
    {
        taskList = new List<Task<object>>();
    }

    public static ImageUtil Instance { get { return Nested.instance; } }

    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as before field init
        static Nested()
        {
        }

        internal static readonly ImageUtil instance = new ImageUtil();
    }

    #endregion

    Queue<Task<Object>> taskList;
    bool isProcessing;
    public async Task<Object> LoadImage(String imageID)
    {
        //Here what I need to put to execute "return await LoadImageInternal(imageID);"
        //one by one. So that if one image is loading and mean time some other thread
        //calls this method then the last thread have to wait until current loading finish.

    }
    private async Task<Object> LoadImageInternal(String imageID)
    {
        //Business Logic for image retrieval.
    }
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*las 6

SemaphoreSlim有一个WaitAsync方法,允许您异步强制执行关键部分:

private readonly SemaphoreSlim loadSemaphore = new SemaphoreSlim(1, 1);

public async Task<Object> LoadImage(String imageID)
{
    await loadSemaphore.WaitAsync();

    try
    {
        return await LoadImageInternal(imageID);
    }
    finally
    {
        loadSemaphore.Release();
    }
}
Run Code Online (Sandbox Code Playgroud)

这种模式在Stephen Toub的文章中提出.