【发布时间】:2015-03-27 13:55:50
【问题描述】:
我有一个正在运行的任务,但我对它的速度不满意,所以我决定把它变成 Parallel.ForEach,因为它更快,谁能帮我把这个函数变成 Parallel.ForEach,谢谢。
private async void run_task()
{
cancellationTokenSource = new CancellationTokenSource();
cancellationToken = cancellationTokenSource.Token;
label20.Text = "";
foreach (var node2 in checkedListBox1.CheckedItems)
{
progressBar1.Value = 0;
rd node = (rd)node2;
node.max_chp = await mc(node.link);
for (int ii = 1; ii <= node.max_chp; ii++)
{
progressBar1.Value = (int)(((decimal)ii / (decimal)node.max_chp) * 100);
byte[] data = null;
string add;
using (WebClient client = new WebClient())
{
client.Proxy = null;
if (ii == 1)
{
add = node.link;
}
else
{
add = node.link + ii.ToString() + ".html";
}
string tem = await get_pics(add, ii - 1);
label20.Text = add;
using (Task<byte[]> task = Task.Factory.StartNew<byte[]>(() => dl_data(client, tem), cancellationToken))
{
try
{
await task;
}
catch
{
dis_GUI(true, 1);
label20.Text = "";
progressBar1.Value = 0;
pictureBox3.Visible = false;
return;
}
data = task.Result;
}
}
string subPath = node.name;
subPath = System.Text.RegularExpressions.Regex.Replace(subPath, "[^0-9a-zA-Z.]+", " ");
subPath = System.Text.RegularExpressions.Regex.Replace(subPath, @"\d+", n => n.Value.PadLeft(3, '0'));
string path = Path.Combine(files, subPath);
System.IO.Directory.CreateDirectory(path);
File.WriteAllBytes(Path.Combine(path, ii.ToString().PadLeft(3, '0') + ".jpg"), data);
}
}
dis_GUI(true, 1);
label20.Text = "";
progressBar1.Value = 0;
pictureBox3.Visible = false;
}
我知道我的代码做得不好,但请放心。
【问题讨论】:
-
我强烈建议您将小部分逻辑提取到单独的方法中。
-
如果不尝试,您将不会获得太多帮助。你的问题是“我想要这个,我想要你为我做这件事”
标签: c# foreach parallel.foreach