gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:20 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com