我正在创建一个应用程序,它执行多个搜索(不同系统)并希望使用线程,以便这些搜索可以同步而不是顺序。我有一些搜索方法如下:
class Employee
{
public DataTable EmployeeSearch_SystemA(object EmployeeID)
{
// search happening here
Thread.Sleep(5000); //simulating a search
// we would return the actual results here
return new DataTable();
}
public DataTable EmployeeSearch_SystemB(object EmployeeID)
{
Thread.Sleep(4000);
return new DataTable();
}
public DataTable EmployeeSearch_SystemC(object EmployeeID)
{
Thread.Sleep(2000);
return new DataTable();
}
}
我可以从我的main方法顺序运行它们:
static void Main(string[] args)
{
Employee e = new Employee();
e.EmployeeSearch_SystemA("ABCDEFG");
e.EmployeeSearch_SystemB("ABCDEFG");
e.EmployeeSearch_SystemC("ABCDEFG");
}
但是对于系统B的搜索,我们需要等待系统A的搜索完成。
如何使用线程执行以下操作:
static void Main(string[] args)
{
// create threads
Thread thSystemA = new Thread(e.EmployeeSearch_SystemA);
Thread thSystemB = new Thread(e.EmployeeSearch_SystemB);
Thread thSystemC = new Thread(e.EmployeeSearch_SystemC);
// run the three searches as individual threads
thSystemA.Start("ABCDEFG");
thSystemB.Start("ABCDEFG");
thSystemC.Start("ABCDEFG");
DataTable resultsSystemA = // get the datatable that EmployeeSearch_SystemA returns
// etc...
}
看来你只能为线程
分配一个void方法答案 0 :(得分:2)
并行化它们应该很容易......
static void Main(string[] args)
{
DataTable resultsSystemA;
DataTable resultsSystemB;
DataTable resultsSystemC;
Employee e = new Employee();
var a = Task.Run(() => { resultsSystemA = e.EmployeeSearch_SystemA(); });
var b = Task.Run(() => { resultsSystemB = e.EmployeeSearch_SystemB(); });
var c = Task.Run(() => { resultsSystemC = e.EmployeeSearch_SystemC(); });
Task.WaitAll(a, b, c);
// use the datatables.
}
...前提是这三种方法实际上是线程安全的和彼此独立。他们都在同一个班级的事实使我有点怀疑,但这是你的工作,以确保他们实际上能够彼此独立行事。