Reputation: 1518
If I have a created a object like this
memberdetail md = new memberdetail(arg0, arg1, arg3)
how can I create a thread for the md object?
Thread t = new Thread((md));
t.Start();
is not working. Thx
Upvotes: 2
Views: 217
Reputation: 10834
Try this if all you want to do is create multiple objects in different threads.
for(int i = 0, i < numThreads; i++)
(new Thread( () =>
{ memberdetail md = new memberdetail(arg0, arg1, arg3) }).start()
Any other actions you want to perform you can do inside the body of the lambda e.g.
for(int i = 0, i < numThreads; i++)
(new Thread( () =>
{
memberdetail md = new memberdetail(arg0, arg1, arg3);
md.ActionOne();
md.ActionTwo();
//Some other actions...
}).start()
Upvotes: 1
Reputation: 31
I would recommend using ThreadPool.QueueUserWorkItem so that the application can manage the thread, and make sure memberdetail inherits from object.
http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
memberdetail md = new memberdetail(arg0, arg1, arg3)
ThreadPool.QueueUserWorkItem(DoWork, md);
private void DoWork(object state)
{
if (state is memberdetail)
{
var md= state as memberdetail;
//DO something with md
}
}
Upvotes: 0
Reputation: 50018
If you want to pass the object into the thread on start, do this:
public class Work
{
public static void Main()
{
memberdetail md = new memberdetail(arg0, arg1, arg3)
Thread newThread = new Thread(Work.DoWork);
// Use the overload of the Start method that has a
// parameter of type Object.
newThread.Start(md);
}
public static void DoWork(object data)
{
Console.WriteLine("Static thread procedure. Data='{0}'", data);
// You can convert it here
memberdetail md = data as memberdetail;
if(md != null)
{
// Use md
}
}
}
See Thread.Start Method (Object) for more details.
Upvotes: 2
Reputation: 273691
You do not create a Thread for an object. Threads are separate.
In most cases you should not be using Threads (anymore). Look at ThreadPool and Tasks (TPL library).
Upvotes: 1
Reputation: 35726
You can't create a thread for objects per se. You can pass an instance of a delegate to be invoked on the thread.
like on MSDN.
Threads do functions not, contain objects.
Upvotes: 0
Reputation: 32768
You have to pass the object's method to the Thread's constructor as below,
Thread t = new Thread(md.SomeFn);
t.Start();
http://msdn.microsoft.com/en-us/library/ms173178(v=vs.80).aspx
Upvotes: 3
Reputation: 76258
You don't start a thread on an object, but rather a method:
memberdetail md = new memberdetail(arg0, arg1, arg3);
Thread t = new Thread(md.DoSomething);
t.Start();
Upvotes: 3