c# - C#中的同步任务执行

标签 c# .net c#-4.0 async-await task-parallel-library

我在 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.
    }
}

最佳答案

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();
    }
}

此模式显示在 Stephen Toub's article 中.

关于c# - C#中的同步任务执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964358/

相关文章:

c# - 从事件 c# 中取消订阅 lambda 表达式

c# - 无法从 GridView 中的 TemplateField 获取文本

.net - SqlProfileProvider

c#-4.0 - MVC 自定义错误页面可以保留路由值吗?

c# - 如何在 C# 中发送 HTTPS GET 请求

c# - 是否可以在 C# 中释放变量?

WPF XAML StringFormat : Culture Workaround broken in C# 4. 0?

C# MongoDB : How can I map a domain object (BsonIgnoreIfDefault needed on Id property)

c# - 字符编码,char 转 xml 值

java - Vector3 赋值似乎被忽略