簡體   English   中英

如何等待 C# 事件處理程序的響應?

[英]How to wait for the response of event handler in C#?

我有一個分為多個層的應用程序 (A1)。 一些層用於用戶交互,一些用於與不同的數據庫交互,一些包含業務邏輯。 我們有另一個第三方應用程序 (A2) 向 (A1) 發送請求,A1 需要響應該請求。 下面是A1的架構。

T3(這一層接收來自A2應用的請求)

T2(業務邏輯)

T1(用戶界面)

T2 包含所有業務邏輯。 我面臨的問題是當我收到來自 A2 應用程序的請求時。 我需要根據 T2 中存在的一些業務邏輯對請求做出響應。 我可以從 T3 調用 T2 訂閱的事件,但我必須從事件處理程序獲取數據,如下所示;

T3:

public Response CanStore(string materialType){
    //Invoke event and wait to get response from T2
    return response.;

}

T2:訂閱了T3的事件

 public async void canStore(object sender, EventArgs e){
     //Perform some logic and response result to T3
}

可能嗎?

在我看來你的架構是錯誤的

如果 T2 有業務邏輯,而 T1 是一個用戶界面,大概需要訪問業務邏輯,而 T3 是一個從外部接收消息並且需要訪問業務邏輯的應用程序,那么 T1 和 T3 都需要引用T2。

那么這只是將業務邏輯依賴注入到 T3 中的簡單一點!

public class T3Service
{
    private readonly IT2BusinessLogic businessLogic;

    public T3Service(IT2BusinessLogic businessLogic)
    {
        this.businessLogic = businessLogic;
    }

    public Response CanStore(string materialType)
    {
        var t2Response = businessLogic.CanStore(materialType);
        // Do what you like to build response to external service
        return response;

    }
}

除了架構問題,假設您可以修改 T3 和 T2,您可以解決濫用 EventArgs 和一些自定義 EventType 的問題。 不是我最喜歡的,但可以解決您的問題。

讓 T2 操作 EventArg 將需要的結果存儲在里面。 事件處理程序完成后,調用站點 T3 可以從 eventArg 獲取結果。

就像是

public Response CanStore(string materialType){
    //Invoke event and wait to get response from T2
    myEvent.Invoke?(sender, myCustomEventArgs);
    await myCustomEvent.Completion.Task;

    return myCustomEvent.ResponseFromSubscriber;
}

使用 myCustomEvent 使用兩個屬性擴展您當前的事件,

MyCustomEventArgs: MyCurrentEventArgs
{
    // makes your Event "awaitable";
    TaskCompletionSource<bool> Completion{ get; } = new TaskCompletionSource<bool>; 
    Response ResponseFromSubscriber{ get; set; } // As you need 
}

和訂戶

public async void canStore(object sender, EventArgs e){
    //Perform some logic and response result to T3
    if(e is MyCustomEventArgs myCustomEventArgs)
    {
        myCustomEventArgs.ResponseFromSubscriber = new Reponse(); // Your whatever 
        myCustomEventArgs.Completion.SetResult(true); // Triggers the Task completion for your awaiting EventInvoker
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM