Multithreading problems with C#

Asked

Viewed 57 times

4

Guys, I’m having a problem doing multithreading on a system with Kinect that I’m developing for my research project.

I understood that this happens because I’m trying to access from a Thread B a resource that is in Thread A, thus launching a System.Invalidoperationexception. The question is, how do I fix it? I really have no idea how to do it (it’s the first time I’m working with more than one thread).

From now on, thank you.

Ah, if you need anything more of the code, please let me know! D

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • 1

    Next time paste the code directly into the question, not into an image! It gets complicated to fix the code, type it and even change it if it is in image :)

  • Thank you Marciano! Next time don’t make that mistake!

1 answer

2


A way to access an object that belongs to another Thread is by means of a Delegate:

private delegate void translateObjectDelegate();

private void translateObject(){
    if (translate.InvokeRequired)
        {
            translateObjectDelegate delegateTO = new translateObjectDelegate(translateObject);
            this.Invoke(delegateTO, null);
        }
    else
        {
             //translate.OffsetX = ..........
             //aqui você continua o método normal
        }
}

First the method checks whether the object is accessible in the Thread current on the line if (translate.InvokeRequired), if it is not accessible, an Delegate and it is invoked, triggering the execution of the method again so that the object is accessible. If the object is accessible from the start, the method will be executed normally.

Some sources for reading on Delegate and Thread/Invoke:

Delegate MSDN

Control.Invoke MSDN

Control.Invokerequired MSDN

  • Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.