C# 同时调用3个函数。应该使用Parallel.For吗?
问题:C# 同时调用3个函数。应该使用Parallel.For吗?,c#,multithreading,C#,Multithreading,问题: 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) {
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);
}
}
}
目前,我在代码中调用了3个函数,这些函数彼此后面执行,需要一些时间才能完成。所以我想知道是否有一种方法可以同时调用它们,例如使用Parallel.for
循环
如果我可以使用并行。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);
}
}
}
private void check()
{
对于(int i=0;i
作为一种快速估计(您是否将获得合理的增益),您可以尝试并行Linq(PLinq)
bool[]results=newfunc[]{function1,function2,function3}
.天冬酰胺()
.AsOrdered()//f(地址))
.ToArray();
bool check1=结果[0];
bool check2=结果[1];
bool check3=结果[2];
只有当3个函数可以并行运行时,您才能回答。异步实现它们中的每一个,或者用任务包装它们,然后等待所有3A并行for循环是错误的方法-您在循环什么?如果您想并行运行每个方法,您需要使用线程或TPL。如果您想保证检查变量和相同编号的函数之间的对应关系,我认为您还需要一个AsOrdered()
s@Damien_The_Unbeliever:接得好!你说得很对-.AsOrdered()
应该放进去,谢谢!这不会仍然按顺序运行功能1
、功能2
和功能3
?在我看来,他实际上想同时执行这些任务。我认为将它们转换为Task
并使用Task。当所有的都更合适时。@Bradley Uffner:不,它不会按顺序运行函数;我们已经准备好了.AsSequential()
AsOrdered()
只是确保结果(数组)的顺序与收入(函数)的顺序相同:results[0]
对应于function1
等。将函数转换为Task
可能很困难(我们不知道这些函数的使用上下文),而且可能看起来没有用(没有收益,但是开销)。这就是为什么我建议使用PLinq作为试金石的原因。