[英]awaiting async method in consumer using BlockingCollection as queue
[英]Return to calling method - BlockingCollection queue items
我需要ConcurrentQueue和BlockingCollection的幫助。
場景是我試圖限制請求並符合每秒1個請求的限制,當我從隊列中取出一個項目時就會發生限制。 該應用程序是MVC 4應用程序,因此在任何給定時間都可能有多個生產者,而我正在聯系的只有一個消費者/ Web服務。
GetUser(string url)
會將請求添加到隊列,請求只是一個URL。 簡而言之,我想處理隊列中的項目,下載響應並將其發送回調用方法。 將其發送回調用方法是即時通訊的問題。 我在這里有什么選擇?
//I want to do something like this, and wait for the throttled response to return
public class WebService()
{
public string GetUser(string name)
{
var url = buildUrl(name);
var response = string.Empty;
var downloadTask = Task.Factory.StartNew( () => {
response = WebServiceHelper.ThrottledDownload(url);
});
downloadTask.Wait();
return response;
}
}
public static class WebServiceHelper()
{
private static BlockingCollection<Request> requests = new BlockingCollection<Request>();
static WebServiceHelper()
{
foreach(var item in requests.GetEnumerableConsumer()) {
string response = DoWork(item.Url);
//How can i send this back to the calling method?
}
}
public static string ThrottledDownload(string url)
{
//Add the request to the blocking queue
requests.Add(new Request(url, someId));
//How do i get the result of the DoWork method?
}
}
您可能不想將結果“返回”給ThrottledDown
方法。 至少我不這么認為。 如果您確實想這樣做,則必須進行某種阻塞呼叫。 或使用具有延續性的Task
...在C#5中可能是async
。
仍然不清楚主線程在做什么。 我假設它正在排隊以一秒鍾為間隔的消費者線程處理一堆請求(大概是為了防止您被查詢的服務器限制)。 然后,您希望通知主線程(或某事),以便它可以……做某事。
您的程序流程仍然不清楚。
根據您希望主線程執行的操作(以及您希望其執行哪些操作的信息),您有很多選擇。 您可以:
BlockingCollection
。 使用者完成請求后,便向該集合添加一個對象。 主線程輪詢該集合以獲取請求完成的通知。 Request
對象添加一個事件(例如, ManualResetEventSlim
)。 使用者完成請求后, Set
在該事件上調用Set
。 主線程要么等待該事件,要么定期對其進行輪詢。 Request
對象中傳遞)。 該回調函數可以通知主線程,記錄結果或任何您喜歡的東西。 同樣,如果沒有有關您的應用程序和要解決的更高級別問題的更多信息,則很難提出更具體的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.