Click to See Complete Forum and Search --> : passing a parameter to a Thread


barbiomalefico
February 13th, 2004, 10:44 AM
I usually use the standard Thread:


Thread ClientThread;
ClientThread = new Thread(new ThreadStart(ClientReceive));
ClientThread.Start();


but now i need to pass a parameter to the Thread Function. How can i do this?

Ciao

pareshgh
February 14th, 2004, 01:33 AM
use ThreadPool

barbiomalefico
February 18th, 2004, 05:12 AM
Could you please post an example.
I have read the documentation of MSDN but don't find any way to pass a struct to a Thread.
For now I have Create an Hashtable with this form:
Key = Thread
Value = myParameter
In the Thread i use GetCurrentThread to chach the myParameter value and access to my data. This is a very bad code, but it works fine. I'm looking for a better merhod.

Ciao

Norfy
February 18th, 2004, 07:09 AM
Did you read this article in MSDN:

Passing Data To Threads (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconCreatingThreads.asp)

Essentially it's saying that one way to pass data to a Thread is to "create an object to hold the data and the thread method".

barbiomalefico
February 18th, 2004, 08:26 AM
I have already see that article.
The first method i have used, i think my way is more clear to read so i use this.
I'm thinking about how much could be hard to override the Thread and ThreadStart class to use a delegate with a single argumento of type Object.
:eek: this way scary me a bit :eek:

Norfy
February 18th, 2004, 08:58 AM
Very hard since Thread is a 'sealed' class. :)

Acephalus
February 18th, 2004, 09:07 AM
There is no way to pass an object as a parameter like you want. Your way is fine for small applications (by small I mean <1-2k lines), but normally you should use the object oriented approach. By encapsulating all thread-related methods in their own class you will have a more maintainable and logically coherent code.

As for overriding Threads... well, Norfy already took care of that, although "very hard" is an understatement... ;)