我編碼一個自定義的C#電報客戶從TLSharp開始,修改了它以支持層54電報客戶端更新和在同一會話API請求
我要處理來自服務器的電報都接收更新和使用API而無需打開單獨的會話來執行此操作。
問題基本上是多線程訪問連接到電報服務器的套接字。
這方案:
TelegramClient < ------- socket_1 [(session_1)] --------> TelegramServer
的問題是,爲了收到我用了一段時間(真)週期電報服務器 基本上都是模式化的不斷更新:
while(true){
data_cipher = await socket_1.receive() // listen for new stuff from the socket_1
data_plain = decrypt(data_cipher) // decrypt
processUpdate(data_plain) // process the update
}
現在,如果我想要的,例如,對於所有的聊天記錄列表中查詢電報服務器中,我是註冊,我有 訪問socket_1以發送此請求,並等待答案,但socket_1正在偵聽,我顯然無法訪問它。
一種解決方案可能是使用的要求更新已被接收後,將被處理的載體, 的想法是這樣的:
List<Request> pending_requests = new List<Request>() // list of requests added by another thread
while(true){
data_cipher = await socket_1.receive() // listen for new stuff from the socket_1
data_plain = decrypt(data_cipher) // decrypt
processUpdate(data_plain) // process the update
if(pending_requests.Count != 0){
foreach(Request r in pending_requests){
processRequest(r)
}
}
}
該解決方案是非常可怕的,因爲我們處理只有更新後的要求,因此沒有更新=沒有請求處理......
另一種可能是使用某種類型的鎖機構下面這樣一個方案:
//Thread_updater
//--------------------------------------------
while(true){
lock(socket_1){
data_cipher = await socket_1.receive() // listen for new stuff from the socket_1
}
data_plain = decrypt(data_cipher) // decrypt
handleUpdate(data_plain) // process the update
}
--------------------------------------------
//Thread_requests
//--------------------------------------------
Request r = new Request(<stuff>);
lock(socket_1){
await sendRequest(r,socket_1)
}
--------------------------------------------
這個問題的最大問題是,一旦Thread_updater接受鎖定,它將永遠不會釋放它,直到接收到更新爲止......這與以前基本相同。 我也嘗試玩取消任務或套接字超時,但我覺得我走錯了路。
有沒有一個優雅的解決方案/模式,以便以一種整潔的方式處理這個問題? 如上所述,我不想打開2個會話,因爲它在邏輯上是錯誤的(這就像有兩個客戶端來處理接收更新和發送消息)。