If you have a PH account, you can customize your PH profile.

C#

Moderators: None (Apply to moderate this forum)
Number of threads: 2409
Number of posts: 5239

This Forum Only
Post New Thread

Report
Cross thread Posted by ravanegmond on 25 Jul 2005 at 12:55 AM
Hello I have a little program I made a very simple udp server. When the program starts a new thread... waiting for any incoming data.

Now my problem is when the incoming data is proccesed I want to put it in textBox1 located on Form1

because textBox1 is created in a other thread I get this error:

System.InvalidOperationException was unhandled
Cross-thread operation not valid: Control 'tbMessages' accessed from a thread other than the thread it was created on.

So I now the problem but I don't have any idea how to solve it I tried things with modifiers but still the same result.

Please help!


Report
Re: Cross thread Posted by iwilld0it on 25 Jul 2005 at 6:38 AM
You use a delegate to set the text property on the main thread. Here is an example:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

public delegate void SetTextDeleg(string text);

namespace WinTestC
{
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.TextBox textBox1;

        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(DoWork));
            t.Start();

            textBox1.Text = string.Empty;
        }

        private void SetText(string text)
        {
            textBox1.Text = text;
        }

        private void DoWork()
        {
            Thread.Sleep(3000);

            textBox1.Invoke(
                new SetTextDeleg(SetText),
                new object[]{"Some Text"});
        }
    }
}


The key functionality is demonstrated in the DoWork thread. A call to the textbox objects Invoke method is used to generate a delegate call (SetTextDeleg) on the main thread to the SetText routine. The second argument is an object array. There should be an object in this array for every argument in the delegate. Finally, the SetText callback does the actual work of setting the textbox text property on the main thread.

Yes, this is alot of work to set a simple property, but i'm sure you can streamline it.

Report
Re: Cross thread Posted by ravanegmond on 25 Jul 2005 at 10:58 AM
: You use a delegate to set the text property on the main thread. Here is an example:
:
:
: using System;
: using System.Drawing;
: using System.Collections;
: using System.ComponentModel;
: using System.Windows.Forms;
: using System.Data;
: using System.Threading;
: 
: public delegate void SetTextDeleg(string text);
: 
: namespace WinTestC
: {
:     public class Form1 : System.Windows.Forms.Form
:     {
:         private System.Windows.Forms.TextBox textBox1;
: 
:         [STAThread]
:         static void Main() 
:         {
:             Application.Run(new Form1());
:         }
: 
:         private void Form1_Load(object sender, System.EventArgs e)
:         {
:             Thread t = new Thread(new ThreadStart(DoWork));
:             t.Start();
: 
:             textBox1.Text = string.Empty;
:         }
: 
:         private void SetText(string text)
:         {
:             textBox1.Text = text;
:         }
: 
:         private void DoWork()
:         {
:             Thread.Sleep(3000);
: 
:             textBox1.Invoke(
:                 new SetTextDeleg(SetText),
:                 new object[]{"Some Text"});
:         }
:     }
: }
: 

:
: The key functionality is demonstrated in the DoWork thread. A call to the textbox objects Invoke method is used to generate a delegate call (SetTextDeleg) on the main thread to the SetText routine. The second argument is an object array. There should be an object in this array for every argument in the delegate. Finally, the SetText callback does the actual work of setting the textbox text property on the main thread.
:
: Yes, this is alot of work to set a simple property, but i'm sure you can streamline it.
:
:

Thank you very very very much. It's works perfectly and so smoothly.
It is the first time I work with multiple threads. I don't know exactly how this solution works but it works;) but if you like to tell, can you explain me the following.

delegate
and object

Thanxz in advance.
Report
Re: Cross thread Posted by iwilld0it on 25 Jul 2005 at 6:59 PM
A delegate is merely a managed function pointer. When you declare a delegate such as:

public delegate void DoSomethingDeleg();


The compiler generates a class that wraps a function that takes no arguments and returns void. Take a look at this example C# Console App:

using System;

namespace DelegCSharp
{
	public delegate void DoSomethingDeleg();

	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);
			doIt += new DoSomethingDeleg(SaySomethingElse);

			doIt();
		}

		public static void SaySomething()
		{
			Console.Write("Hello");
		}

		public static void SaySomethingElse()
		{
			Console.WriteLine(" World");
		}
	}
}


This line:

DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);


Creates a function pointer to the function called SaySomething.

This line:

doIt += new DoSomethingDeleg(SaySomethingElse);


looks strange, but to explain, delegates maintain a list of function pointers of the same type. The += operator says to add another function to that list. This is called multicasting and in fact the class that the compiler generates for the delegate, derives from MultiCastDelegate.

Finally, this line:

doIt();


Calls all the functions in the delegate, in the order they were added. So basically this single line of code calls the SaySomething function followed by the SaySomethingElse function. Cool huh.

Delegates are also used for generating call backs:

public static void CallBackSayIt(DoSomethingDeleg sayIt)
{
   if(null != sayIt)
      sayIt();
}


To use this function you could ...

CallBackSayIt(new DoSomethingDeleg(SaySomething));


Delegates are also used to handle events and such. Also, you are probably wondering why a delagate is needed to set the property of a text box control on the main thread from a secondary thread. The reason is because delegates are always triggered from the main thread.

Delegates are difficult to get use to, but with practice, you can accomplish some advanced techniques.
---------------------------------------------------------------------

Object
------

All classes derive directly or indirectly from an object variable. You can store anything in an object.

object obj = 17;
obj = "Hello";
obj = new StringBuilder();
// etc ...

Report
Re: Cross thread Posted by ravanegmond on 26 Jul 2005 at 1:35 AM
: A delegate is merely a managed function pointer. When you declare a delegate such as:
:
:
: public delegate void DoSomethingDeleg();
: 

:
: The compiler generates a class that wraps a function that takes no arguments and returns void. Take a look at this example C# Console App:
:
:
: using System;
: 
: namespace DelegCSharp
: {
: 	public delegate void DoSomethingDeleg();
: 
: 	/// <summary>
: 	/// Summary description for Class1.
: 	/// </summary>
: 	class Class1
: 	{
: 		/// <summary>
: 		/// The main entry point for the application.
: 		/// </summary>
: 		[STAThread]
: 		static void Main(string[] args)
: 		{
: 			DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);
: 			doIt += new DoSomethingDeleg(SaySomethingElse);
: 
: 			doIt();
: 		}
: 
: 		public static void SaySomething()
: 		{
: 			Console.Write("Hello");
: 		}
: 
: 		public static void SaySomethingElse()
: 		{
: 			Console.WriteLine(" World");
: 		}
: 	}
: }
: 

:
: This line:
:
:
: DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);
: 

:
: Creates a function pointer to the function called SaySomething.
:
: This line:
:
:
: doIt += new DoSomethingDeleg(SaySomethingElse);
: 

:
: looks strange, but to explain, delegates maintain a list of function pointers of the same type. The += operator says to add another function to that list. This is called multicasting and in fact the class that the compiler generates for the delegate, derives from MultiCastDelegate.
:
: Finally, this line:
:
:
: doIt();
: 

:
: Calls all the functions in the delegate, in the order they were added. So basically this single line of code calls the SaySomething function followed by the SaySomethingElse function. Cool huh.
:
: Delegates are also used for generating call backs:
:
:
: public static void CallBackSayIt(DoSomethingDeleg sayIt)
: {
:    if(null != sayIt)
:       sayIt();
: }
: 

:
: To use this function you could ...
:
:
: CallBackSayIt(new DoSomethingDeleg(SaySomething));
: 

:
: Delegates are also used to handle events and such. Also, you are probably wondering why a delagate is needed to set the property of a text box control on the main thread from a secondary thread. The reason is because delegates are always triggered from the main thread.
:
: Delegates are difficult to get use to, but with practice, you can accomplish some advanced techniques.
: ---------------------------------------------------------------------
:
: Object
: ------
:
: All classes derive directly or indirectly from an object variable. You can store anything in an object.
:
:
: object obj = 17;
: obj = "Hello";
: obj = new StringBuilder();
: // etc ...
: 

:

Thanxz




 
Popular resources and forums for programmers on Programmersheaven.com
Assembly, Basic, C, C#, C++, Delphi, Java, JavaScript, Pascal, Perl, PHP, Python, Ruby, Visual Basic
© Copyright 2009 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Publisher: Lars Hagelin. Read the latest words from the publisher here.
Be the first to sign up for Lars Hagelin’s In-depth Outsourcing Newsletter here.
bootstrapLabs Logo A bootstrapLabs project.