问题:
我目前在我的代码中调用了3个函数,这些函数在彼此后面执行,这需要一些时间才能完成。所以我想知道是否有办法同时调用它们,例如使用Parallel.For
循环。
如果我可以使用Parallel.For
循环,我将如何设法执行此操作?这是使用它的正确方法吗?
Parallel.For(0, 1, i =>
{
bool check1 = function1(address);
bool check2 = function2(address);
bool check3 = function3(address);
});
我目前的代码:
private void check()
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
string address = dataGridView1.Rows[i].Cells[0].Value.ToString();
try
{
if (address.Length < 6)
{
// Those 3 functions are currently called behind each other
// Could those be called inside a Parallel.For loop at the same time?
bool check1 = function1(address);
bool check2 = function2(address);
bool check3 = function3(address);
}
else
{
dataGridView1.Rows[i].Cells[2].Value = "Error";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
答案 0 :(得分:4)
作为快速估算(您将获得合理的收益),您可以尝试 Parallel Linq ( PLinq )。
bool[] results = new Func<string, bool>[] {function1, function2, function3}
.AsParallel()
.AsOrdered() // <- to guarantee function / outcome correspondence
.Select(f => f(address))
.ToArray();
bool check1 = results[0];
bool check2 = results[1];
bool check3 = results[2];