egramtel/tdsharp

Threading in WPF with TDLib 1.8

antonGritsenko opened this issue · 5 comments

I do have the WPF application that do the very simple parsing of incoming messages and display them in the grid. Part of the process, for sure, is getting chats. It works just well with TDLib v.1.7.x, but few days ago I decide to upgraded the app to use the version 1.8.1, and now the GetChat method just stop working.

The message from the TDLib routed using simple event to the main window class. The event contains the message id and chat id. When message received in the main window, I'm getting the chat (_client is TDLib itself here, just for simplification):

private void OnNewMessageReceived(object sender, TelegramClient.NewMessageReceivedEventArgs e)
{
......
    var tdChat = await _client.ExecuteAsync(new TdApi.GetChat { ChatId = chatId });
}

and this part is never ending, so it looks like the thread blocking.

So my question is: how to work with TDLib 1.8 regarding threading? Am I have to execute all TDLib code in the main WPF thread?

It works just well with TDLib v.1.7.x

Could you please clarify what's the x here? There were some threading changes between 1.7.0 and 1.7.0.1 (no less). But they should've been improved the situation in GUI apps (since we no longer require the UI thread for any tdlib-related calls).

Is it possible that the thread pool in your app is either limited or exhausted?

@ForNeVeR it was 1.7.9 where it works.

Is it possible that the thread pool in your app is either limited or exhausted?

Shouldn't be. Actually, its the same app as I shared with you in #109

OK, here is the repro steps:

  1. Take the app from the private repo shared in #109
  2. Make it work :)
  3. Log in
  4. Send any message to the logged in number

Result: the event handler _client_NewMessageReceived never finished, because of the _telegramClient.MarkMessageRead, which executes the ViewMessagesAsync of the TDLib, The execution ViewMessagesAsync never ends.

Here is what I got from the main TDLib team as a reminder:

Also. since TDLib 1.8 updates for all clients need to be received in the same thread, which could affect tdsharp usage of TDLib.

Could this be related?

I've found the workaround: turn _client_NewMessageReceived to async and then put the await Task.Delay(1) in the beginning of the event handler.
Found this here: https://weblog.west-wind.com/posts/2022/Apr/22/Async-and-Async-Void-Event-Handling-in-WPF#another-alternative-top-level-await-operation . Btw, the method with using Dispatcher doesn't work.

But again, with 1.7.9 same works fine.

Yep, an obvious deadlock in async code. Please avoid using Task.Result or GetAwaiter().GetResult() in a GUI app always.