我正在尝试根据程序收到的值创建多个线程。 我使用以下代码。
int count = 7;
Class1 cl=new Class1();
for (int i = 0; i < count; i++)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs argss)
{
BackgroundWorker b = o as BackgroundWorker;
cl.print("id","password");
});
}
Console.ReadLine();
在class1的print()方法中,我打印一行&#34;刚输入打印功能&#34;。
但是当我运行程序时,没有打印任何行。
答案 0 :(得分:2)
您需要启动后台线程。
class Program
{
static void Main()
{
int count = 7;
Class1 cl = new Class1();
for (int i = 0; i < count; i++)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs argss)
{
BackgroundWorker b = o as BackgroundWorker;
cl.Print("id", "password");
});
bw.RunWorkerAsync();//Start the background here
}
Console.ReadLine();
}
}
class Class1
{
public void Print(string id, string password)
{
Console.WriteLine("Id:{0},Password:{1}", id, password);
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
如果您使用.Net 4.5,您可以节省一些击键并使用TPL
for (int i = 0; i < count; i++)
{
Task.Run(() => cl.Print("id","password"));
}