Results 1 to 12 of 12

Thread: [RESOLVED] thread safe calls to a windows forms controls??

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Resolved [RESOLVED] thread safe calls to a windows forms controls??

    I have downloaded a client server chat-type application that accompanies a tutorial. It was written in c#.net 2003, i have .net 2005.

    There are two projects, client side and a server side.

    It converted both the projects successfully, but when i try to run the projects it highlights the following line of code in the server side app, and says the thread has made an "unsafe call to a windows form control". I use the help, but am completely confused about what to do.

    Please someone help!

    ok, here is the line of code it highlights:

    txtDataRx.Text = txtDataRx.Text + szData;

    here are the surrounding lines of code:

    {
    CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
    //end receive...
    int iRx = 0 ;
    iRx = theSockId.thisSocket.EndReceive (asyn);
    char[] chars = new char[iRx + 1];
    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
    int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
    System.String szData = new System.String(chars);
    txtDataRx.Text = txtDataRx.Text + szData; //this is the line
    WaitForData(m_socWorker );
    }

    here is the relevant extracted section from the help:

    // This event handler creates a thread that calls a
    // Windows Forms control in a thread-safe way.
    private void setTextSafeBtn_Click(
    object sender,
    EventArgs e)
    {
    this.demoThread =
    new Thread(new ThreadStart(this.ThreadProcSafe));

    this.demoThread.Start();
    }

    // This method is executed on the worker thread and makes
    // a thread-safe call on the TextBox control.
    private void ThreadProcSafe()
    {
    this.SetText("This text was set safely.");
    }

    I have just started this network c# programming, and that is y i am confused about what to do!

    Any help would be greatly appreciated.

    GTJ

    ps. should this thread go into the network programming forum instead??

    ps.Should i attach the projects to this thread so u can all experience the problem??

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: thread safe calls to a windows forms controls??

    You are supposed to use a delegate to access control members across thread boundaries. You were supposed to do this in .NET 1.1 but it was not enforced. Here's an example of using the MethodInvoker delegate, which is part of the .NET Framework, to access a control member.
    Code:
            private void SomeMethod()
            {
                if (this.textBox1.InvokeRequired)
                {
                    // This code is not executing on the UI thread so invoke a method on the UI thread via a delegate.
                    this.Invoke(new MethodInvoker(DisplayTextBoxContents));
                }
                else
                {
                    // This code is executing on the UI thread so access the control member directly.
                    MessageBox.Show(this.textBox1.Text);
                }
            }
    
            private void DisplayTextBoxContents()
            {
                MessageBox.Show(this.textBox1.Text);
            }
    The signature of the delegate must match the signature of the method being invoked, so you can use the existing MethodInvoker delegate if your method has no arguments and doesn't return a value. If the method doesn't have that signature than you must declare your own delegate. Here's an example of that.
    Code:
            private void SomeMethod()
            {
                if (this.textBox1.InvokeRequired)
                {
                    // This code is not executing on the UI thread so invoke a method on the UI thread via a delegate.
                    // The second parameter is an array containing the parameters to pass to the method being invoked.
                    this.Invoke(new SetTextBoxContentsDelegate(SetTextBoxContents), new object[] { "SomeString" });
                }
                else
                {
                    // This code is executing on the UI thread so access the control member directly.
                    this.textBox1.Text = "SomeString";
                }
            }
    
            // The signature of this delegate matches the signature of the method it will be used to invoke.
            private delegate void SetTextBoxContentsDelegate(string text);
    
            private void SetTextBoxContents(string text)
            {
                this.textBox1.Text = text;
            }
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: thread safe calls to a windows forms controls??

    ok, i basically understand

    so i need to change this:

    txtDataRx.Text = txtDataRx.Text + szData;

    to something like this:

    ...

    if (txtDataRx.InvokeRequired)
    {

    this.Invoke(new SetTextBoxContentsDelegate(SetTextBoxContents), new object[] { txtDataRx.text + szData });
    }
    else
    {
    txtDataRx.Text = txtDataRx.text + szData;
    }
    }

    private delegate void SetTextBoxContentsDelegate(string text);

    private void SetTextBoxContents(string text)
    {
    txtDataRx.Text = text;
    }

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: thread safe calls to a windows forms controls??

    No, that's no good because you are still accessing the Text property of the TextBox in the other thread. You would have to define a method that appended a string to the existing Text and invoke that instead.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: thread safe calls to a windows forms controls??

    could i just add the text of the box to a variable, append to the variable then write the variable to the text box??

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: thread safe calls to a windows forms controls??

    Whatever you do with any member of the TextBox must be done in the method you invoke. That's the whole point of invoking the method on the UI thread in the first place.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: thread safe calls to a windows forms controls??

    ok, sorry i am pretty confused now, could you send me the code that will fix my problem??

    PLEASE????!!!

    :-)

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: thread safe calls to a windows forms controls??

    What do you want to do? You want to append a string to the Text property of a TextBox, right? Do that in the method you are invoking, which is SetTextBoxContents. It is the string that you want to append that you then need to add to the object array and pass as the second argument to Invoke.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: thread safe calls to a windows forms controls??

    ok, so in your second code example replace "somestring" with the variable containing txtDataRx + szData??

  10. #10

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: thread safe calls to a windows forms controls??

    i just tried what i thought u were saying and it worked!!!

    Thanks for all your help.

    Added positively to reputation!

    Cheers

    GTJ

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] thread safe calls to a windows forms controls??

    I'm glad that you worked it out for yourself, which was the reason that I was reticent to post code. You learn more by doing ti yourself because not only do you get the solution, you also get the methodology for solving similar problems in future. Just one more thing. It occurred to me that, given that the TextBox has an AppendText method itself, you don't even have to write your own method. You simply need to declare a delegate with a a signature that matches TextBox.AppendText and then Invoke that. If that confuses you further then don't worry about it. When you have more experience with delegates and you fully understand what they are doing it will all seem clear.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    England
    Posts
    283

    Re: [RESOLVED] thread safe calls to a windows forms controls??

    yer i agree, i try to solve things myself, but this one i couldn't work out at all. but ur help made it click in my brain suddenly and it feels well good now ive sorted it!! i semi-understand ur new idea, but now it is fixed i think i will leave it.

    Thanks again.

    GTJ

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width