第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

C# 使用 Action 同步 HashSet

C# 使用 Action 同步 HashSet

C#
胡子哥哥 2023-08-20 14:57:33
我有一個(gè)問題,我有一個(gè)簡(jiǎn)單的訂閱者和簡(jiǎn)單的發(fā)布者,它們看起來像: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()}主要想法是我通過一些請(qǐng)求向某些服務(wù)發(fā)送消息并等待到達(dá)(我知道我可以使用 rpc,但可以有任何服務(wù)并且 rpc 不支持主題),這條路徑有效,問題是 requestKeys HashSet 它類中的一個(gè)字段private readonly HashSet<byte[]> requestKeys;正如您在每個(gè)方法調(diào)用中看到的那樣,我將 Key 添加到該字段,如果我發(fā)出第一個(gè)請(qǐng)求,它可以正常工作,但其他請(qǐng)求不會(huì)更新此密鑰集合,我的意思是在 Action 之外它會(huì)更新,但在它之外是一個(gè)問題。我能做什么來解決這個(gè)問題?
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊

如果您想SendRequest()在收到響應(yīng)之前阻止完成,您可以使用 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();

}


查看完整回答
反對(duì) 回復(fù) 2023-08-20
  • 1 回答
  • 0 關(guān)注
  • 119 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)