开发者

creating thread using c#

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


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();


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


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.


  1. You do not create a Thread for an object. Threads are separate.

  2. In most cases you should not be using Threads (anymore). Look at ThreadPool and Tasks (TPL library).


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()


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.


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
       }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜