showpath
showpath

Reputation: 1

Why doesn't my draw function work when called on a different thread?

I'm making a client that connects to a server and sends and receives data. But when the draw function is called from the receiving thread it doesn't draw anything. Though if I call it from my button it draws correctly. Can someone help me please?

Note: It works from a button when I pass it the parameters but not from my other thread getting the receives.

The GetColor() method does work — I've tested it and it draws correctly from a button but not from my receive thread.

public void Draw(int x, int y, int b)
{
    MessageBox.Show(x + " " + y + " " + b);
    Graphics g = this.CreateGraphics();
    Pen pen = new Pen(getcolor(b), 1);
    g.FillRectangle(pen.Brush, x, y, 1, 1);
}

i tried invoke but i think i messed up or something if someone could tell me whats wrong with this code thanks

public void Draw(int x, int y, int b) {

    if (this.InvokeRequired)
    {
        // Reinvoke the same method if necessary        
        BeginInvoke(new MethodInvoker(delegate() { Draw(x, y, b); }));
    }
    else
    {
        MessageBox.Show(x + " " + y + " " + b);
        Graphics g = this.CreateGraphics();
        Pen pen = new Pen(getcolor(b), 1);
        g.FillRectangle(pen.Brush, x, y, 1, 1);
    }}

Thanks

Upvotes: 0

Views: 194

Answers (1)

Peter
Peter

Reputation: 38515

You could use InvokeRequired and Invoke to ensure that you Draw function is called by the gui thread!

Upvotes: 2

Related Questions