Link to home
Start Free TrialLog in
Avatar of Susurrus
Susurrus

asked on

passing objects to a thread

I want to pass several objects into a thread at start and I am not sure how to go about it.  I have seen examples of passing objects using "ParameterizedThreadStart" which are very simple to impliment, but only allow for one object.  How would I go about passing severl objects and/or variables into a new thread?

Thanks in advance for any and all help!
Avatar of margajet24
margajet24
Flag of Singapore image

1. how about creating a structure that constains your data?

2. or a class that contains you data..

3. you can also try to have a the variables public so that it can be accessible to the thread
- the only problem here is when you have more than 1 thread which requires synchronization
because threads might access and overwrite the variables..
Avatar of Susurrus
Susurrus

ASKER

I would rather not use publc variables, for the reasons you point out. How would I go about passing a class that contains the data?
Another alternative is to use ThreadPool.QueueUserWorkItem(callback, state).
Note that the signature of the callback function is different from Thread.Start().
ThreadPool uses WaitCallback, so your thread method should be declared like this:


public void Run(object state)
{
// blah ...
}

The input argument state is the second object that you passed to ThreadPool.QueueUserWorkItem
SOLUTION
Avatar of margajet24
margajet24
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if your objects have the same data type, use the generic List<> to make it type-safe, but you can try to make a List type but you have to check the data type of each object before you use it to avoid problems

but if otherwise, you can use what Mishu007 said above..
thanks!

Mishu007's idea suits me best as I find it the easiest to implement, all ideas have helped me understand the issues.

Cheers :)