您好我想将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秒内将其终止。 请帮忙......提前致谢。
答案 0 :(得分:0)
1-当您将newThread[i]
传递给PasParamsToThrdFunc
时,它为空。将其更改为i
2-您可能需要避免closing over变量i
和time
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)
我可以看到一些问题:
尝试这样的事情:
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);
}
}
}