CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2011
    Posts
    3

    Quite new and stuck with "threads"

    Hi, im trying to get my head around threads or a way to this?

    at the moment i have a method that creates a socket sends a string then waits for a return string and stores in inside a variable.

    It worked fine to start with but i nocticed my window would freeze because it is using the same thread whilts its "waiting" the data back from the socket client.

    So i then put it inside background worker and got it working ok, but i wanted to also put this into its own class.

    And thats where ive lost the plot.

    I now have the mothod in a class, so i can simply create an instance with a contructor which is the string to send then theres on procedure thats connect and send.

    but i want this to happen in the background then one a string or error returns display it inside a textbox.

    What is the correct method for doing this?

    i am quite new to C# so please bare with me.

    Thanks
    Andy

  2. #2
    Join Date
    Feb 2012
    Posts
    5

    Re: Quite new and stuck with "threads"

    Hey,

    From my experience, the basic way a thread works in C# is this.

    Using multiple threads will allow the processes to take turns in the processor, making it seem like they are running concurrently. You create a thread, handing it either a ThreadStart or ParameterizedThreadStart method, then start it. The method usually contains an infinite loop.

    So,

    Code:
    //Semi Psuedo-code
    
    using System.Threading;
    
    Main(...)
    {
    	Thread thread = new Thread(new ThreadStart(MethodToRun));
    	thread.Start()
    }
    
    MethodToRun()
    {
    	while(true)
    	{
    		if(ThreadShouldEnd)
    			break;
    		//things here will wait or be repeated as needed
    	}
    }
    
    //Likewise, if you need to pass an object to the method, use this
    
    Main(...)
    {
    	SomeClass x;
    	Thread thread = new Thread(new ParameterizedThreadStart(MethodToRun));
    	thread.Start(x)
    }
    
    MethodToRun(object o)
    {
    	SomeClass x = (SomeClass)o; //cast object to SomeClass as needed
    	while(true)
    	{
    		if(ThreadShouldEnd)
    			break;
    		//things here will wait or be repeated as needed
    	}
    }

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

Featured