如何在for循环中调用Thread

时间:2012-11-12 13:35:10

标签: c# multithreading delegates

您好我想将sleeptime和Thread Object传递给方法并在for循环中调用该方法。 请参阅下面的代码

public delegate void PasParamsToThrdFunc(int integer, object obj2);
class Program
{
    Thread[] newThread=new Thread[10];

    static void Main(string[] args)
    {
        Program pr = new Program();
        pr.ThreadDeclaration();
        Console.Read();
    }

    public void ThreadDeclaration()
    {
        int time = 5000;
        for(int i=1;i<3;i++)
        {
            time = time * i;
            string s = i.ToString();
            ThreadStart starter = () => PasParamsToThrdFunc(time, newThread[i]);
            newThread[i] = new Thread(starter);
            newThread[i].Name = i.ToString();
            newThread[i].Start();
        }

    }

    public void PasParamsToThrdFunc(int waitTime, Thread obj)
    {
        Thread.Sleep(waitTime);
        Console.WriteLine("" + waitTime + " seconds completed and method is called for thread"+obj.Name+"");
        obj.Abort();
    }
  }

我希望在5秒后调用第一个线程并杀死该对象并对第二个线程执行相同的操作并在10秒内将其终止。 请帮忙......提前致谢。

2 个答案:

答案 0 :(得分:0)

1-当您将newThread[i]传递给PasParamsToThrdFunc时,它为空。将其更改为i

2-您可能需要避免closing over变量itime

public void ThreadDeclaration()
{
    int time = 5000;
    for (int i = 1; i < 3; i++)
    {
        int J = i; // <----
        int timez = time * i; // <----
        string s = i.ToString();

        ThreadStart starter = () => PasParamsToThrdFunc(timez, J);
        newThread[i] = new Thread(starter);
        newThread[i].Name = i.ToString();
        newThread[i].Start(); 
    }

}

public void PasParamsToThrdFunc(int waitTime, int i )
{
    Thread.Sleep(waitTime);
    Console.WriteLine("" + waitTime + " seconds completed and method is called for thread" + newThread[i].Name + "");
    newThread[i].Abort(); // <-- No need
}

答案 1 :(得分:0)

我可以看到一些问题:

  • 您正在使用传递给线程函数的参数访问已修改的闭包(在传递它们之后不应修改这些参数)。
  • 您将线程的句柄传递给自己,然后使用它来中止自己。没必要这样做,因为它会在睡眠后退出。
  • 您通过在每次迭代时将自身乘以i而不是使用时间间隔* i来错误地计算时间。

尝试这样的事情:

using System;
using System.Threading;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.ThreadDeclaration();
            Console.Read();
        }

        public void ThreadDeclaration()
        {
            int timeInterval = 5000;

            for (int i=1; i<3; i++)
            {
                int time = timeInterval * i;
                ThreadStart starter = () => PasParamsToThrdFunc(time);
                var thread = new Thread(starter) {Name = i.ToString()};
                thread.Start();
            }
        }

        public void PasParamsToThrdFunc(int waitTime)
        {
            Thread.Sleep(waitTime);
            Console.WriteLine("" + waitTime + " seconds completed and method is called for thread" + Thread.CurrentThread.Name);

        }
    }
}