V
V
ViceInc2021-11-22 23:12:32
C++ / C#
ViceInc, 2021-11-22 23:12:32

How to run Invoke not from the main thread?

I've used this before and it worked. Then suddenly he began to swear at Invoke

public class ClientHandler
    {
        //Поля
        private Socket handler;
        private Thread thread;
        private int errorsCount;
        public bool finished;
        
        public delegate void RSAPublicKeyMessageHandler(RSAPublicKeyMessage message);
        public event RSAPublicKeyMessageHandler RSAPublicKeyMessageReceived;

        

        private ClientHandler(Socket socket)
        {
            handler = socket;
            finished = false;
            errorsCount = 0;

            StartAsync();
        }

        public async void StartAsync()
        {
            await Task.Run(() => Start());
        }

        public void Start()
        {
                //..............
                BaseMessage outputMessage = Do(inputMessage);
                //..............
        }







        private BaseMessage Do(BaseMessage inputMessage)
        {
            try
            {
                if(inputMessage is RSAPublicKeyMessage rSAPublicKeyMessage)
                {
                    //Вот этот Invoke не выполянется, потому что владелец объекта другой поток
                    RSAPublicKeyMessageReceived?.Invoke(rSAPublicKeyMessage);
                    return new ServiceMessage(false, "OK");
                }
            }
            catch (Exception ex)
            {
                return new ServiceMessage(true, ex.Message);
            }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
ViceInc, 2021-11-23
@ViceInc

I did the project in a fast way and did not do it for the ViewModel window.
I subscribed to an event from the window class itself, this was the problem.
It was necessary to make a ViewModel for the window and subscribe to the event from there

D
Davilkus Games, 2021-11-22
@Davilkus

Try it with Dispatcher
This is for WPF I use
Once dug up, now I use this:
When updating UI:
this.Dispatcher.Invoke(() =>
{
...// your code here.
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question