使用c#创建线程

本文关键字:线程 创建 使用 | 更新日期: 2023-09-27 18:04:32

如果我创建了一个像这样的对象

memberdetail md = new memberdetail(arg0, arg1, arg3)

我如何为md对象创建一个线程?

Thread t = new Thread((md));
t.Start();

不能工作。Thx

使用c#创建线程

不是在对象上启动线程,而是在方法上启动线程:

memberdetail md = new memberdetail(arg0, arg1, arg3);
Thread t = new Thread(md.DoSomething);   
t.Start();

你必须像下面这样把对象的方法传递给线程的构造函数,

Thread t = new Thread(md.SomeFn);
t.Start();

http://msdn.microsoft.com/en-us/library/ms173178 (v = vs.80) . aspx

如果你想在启动时将对象传递给线程,请这样做:

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

看到线程。

  1. 不能为对象创建线程。

  2. 在大多数情况下,你不应该使用线程(不再)。查看ThreadPool和Tasks (TPL库)

如果你想在不同的线程中创建多个对象,可以试试这个。

for(int i = 0, i < numThreads; i++)
    (new Thread( () => 
        { memberdetail md = new memberdetail(arg0, arg1, arg3) }).start()

你想执行的任何其他操作都可以在lambda的主体内执行,例如

for(int i = 0, i < numThreads; i++)
    (new Thread( () => 
        {
            memberdetail md = new memberdetail(arg0, arg1, arg3);
            md.ActionOne();
            md.ActionTwo();
            //Some other actions...
        }).start()

不能为对象本身创建线程。您可以传递一个委托的实例,以便在线程上调用。

类似于MSDN。

线程做函数,不包含对象。

建议使用ThreadPool。QueueUserWorkItem,以便应用程序可以管理线程,并确保memberdetail继承自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
       }
    }