亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# 使用 Action 同步 HashSet

C# 使用 Action 同步 HashSet

C#
胡子哥哥 2023-08-20 14:57:33
我有一個問題,我有一個簡單的訂閱者和簡單的發布者,它們看起來像:public async Task SendRequest(){    var topic = "SomeTopic";    var requestHash = Helpers.ReturnUniqueKey(DateTime.Now, topic);    requestKeys.Add(requestHash);    Console.WriteLine($"Key count {requestKeys.Count}");    var responseHandler = new Action<ResponseMessage>(response =>    {        Console.WriteLine($"Key count {requestKeys.Count}");        foreach (var key in requestKeys)        {            Console.WriteLine($"Response { BitConverter.ToString(response.IdentyficationHash) } - Key { BitConverter.ToString(key) }");            if (!key.SequenceEqual(response.IdentyficationHash)) return;            requestKeys.Remove(key);        }    });    bus.Subscribe(BusController.ManualRequest, responseHandler, configuration => configuration.WithTopic(BusController.ManualRequest));    bus.Publish(someRequest, topic);    async Task WaitForItToWorkAsync()    {        var retry = 0;        var complete = false;        while (!complete)        {            if (retry >= 20) return ; // Ill ass some msg leater            complete = !requestKeys.Contains(requestHash);            retry += 1;            await Task.Delay(1000);         }         return // Ill ass some msg leater      }        await WaitForItToWorkAsync()}主要想法是我通過一些請求向某些服務發送消息并等待到達(我知道我可以使用 rpc,但可以有任何服務并且 rpc 不支持主題),這條路徑有效,問題是 requestKeys HashSet 它類中的一個字段private readonly HashSet<byte[]> requestKeys;正如您在每個方法調用中看到的那樣,我將 Key 添加到該字段,如果我發出第一個請求,它可以正常工作,但其他請求不會更新此密鑰集合,我的意思是在 Action 之外它會更新,但在它之外是一個問題。我能做什么來解決這個問題?
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

如果您想SendRequest()在收到響應之前阻止完成,您可以使用 aSemaphoreSlim而不是在 a 中添加和刪除鍵HashSet,例如:


public async Task SendRequest()

{

    var topic = "SomeTopic";


    SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 1);

    var responseHandler = new Action<ResponseMessage>(response =>

    {

        //signal that the response has arrived

        semaphoreSlim.Release();

    });

    bus.Subscribe(BusController.ManualRequest, responseHandler, configuration => configuration.WithTopic(BusController.ManualRequest));

    bus.Publish(someRequest, topic);


    //wait for the response to arrive

    await semaphoreSlim.WaitAsync();

    semaphoreSlim.Dispose();

}


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號