【发布时间】:2015-11-23 05:15:31
【问题描述】:
我有一个 Windows 窗体应用程序,它可以复制 GEDCOM 系谱文件中的图像引用并重新调整其大小。用户从主窗体中选择文件和输出目录以及调整大小选项,然后打开另一个窗体作为包含标签、进度条和按钮的对话框。我正在更新应用程序以使用 .NET 4.5 中的新异步功能,并对其进行修改以利用并行处理。一切正常,除了我注意到 UI 响应有点不稳定(口吃);如果我不使用百分比更新消息标签,那么它会更顺畅。此外,当我取消任务时,UI 将挂起 1 到 15 秒。该应用程序仅供我个人使用,所以没什么大不了的,但我很好奇可能导致问题的原因以及处理它的推荐方法是什么。并行处理是否只是因为有太多线程需要处理而使 CPU 过载?我尝试在每个循环迭代中添加一个 Thread.Sleep(100),它似乎有点帮助。
这是仍然会导致问题的应用程序的最小版本。重现:
- 使用以下表单创建一个新的 Windows 窗体应用程序。
- 用一堆jpeg图片(50+图片)创建一个目录
- 将 _SourceDirectoryPath 和 _DestinationDirectoryPath 变量替换为您的目录。
- 运行应用程序
Designer.cs:
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblMessage = new System.Windows.Forms.Label();
this.pgProgressBar = new System.Windows.Forms.ProgressBar();
this.btnStart = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblMessage
//
this.lblMessage.AutoSize = true;
this.lblMessage.Location = new System.Drawing.Point(32, 25);
this.lblMessage.Name = "lblMessage";
this.lblMessage.Size = new System.Drawing.Size(0, 13);
this.lblMessage.TabIndex = 0;
//
// pgProgressBar
//
this.pgProgressBar.Location = new System.Drawing.Point(35, 51);
this.pgProgressBar.Name = "pgProgressBar";
this.pgProgressBar.Size = new System.Drawing.Size(253, 23);
this.pgProgressBar.TabIndex = 1;
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(132, 97);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(75, 23);
this.btnStart.TabIndex = 2;
this.btnStart.Text = "Start";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(213, 97);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(315, 149);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.pgProgressBar);
this.Controls.Add(this.lblMessage);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblMessage;
private System.Windows.Forms.ProgressBar pgProgressBar;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnCancel;
}
代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class Form1 : Form
{
private CancellationTokenSource _CancelSource;
private string _SourceDirectoryPath = @"Your\Source\Directory";
private string _DestinationDirectoryPath = @"Your\Destination\Directory";
public Form1()
{
InitializeComponent();
lblMessage.Text = "Click Start to begin extracting images";
btnCancel.Enabled = false;
_CancelSource = new CancellationTokenSource();
}
private async void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnCancel.Enabled = true;
List<string> files = await Task.Run(() => Directory.GetFiles(_SourceDirectoryPath, "*.jpg").ToList());
// scan/extract files
Progress<int> progress = new Progress<int>(UpdateProgress);
int result = await Task.Run(() => ExtractFiles(files, progress, _CancelSource.Token));
if (_CancelSource.IsCancellationRequested)
{
lblMessage.Text = "Extraction cancelled by user.";
}
else
{
lblMessage.Text = string.Format("Extraction Complete: {0} files extracted.", result);
}
btnStart.Enabled = true;
btnCancel.Enabled = false;
}
private void btnCancel_Click(object sender, EventArgs e)
{
lblMessage.Text = "Cancelling...";
btnCancel.Enabled = false;
_CancelSource.Cancel();
}
private void UpdateProgress(int value)
{
lblMessage.Text = string.Format("Extracting files: {0}%", value);
pgProgressBar.Value = value;
}
public int ExtractFiles(List<string> fileReferences, IProgress<int> progress, CancellationToken cancelToken)
{
double totalFiles = fileReferences.Count;
int processedCount = 0;
int extractedCount = 0;
int previousPercent = 0;
Directory.CreateDirectory(_DestinationDirectoryPath);
Parallel.ForEach(fileReferences, (reference, state) =>
{
if (cancelToken.IsCancellationRequested)
{
state.Break();
}
string fileName = Path.GetFileName(reference);
string filePath = Path.Combine(_DestinationDirectoryPath, fileName);
using (Image image = Image.FromFile(reference))
{
using (Image newImage = ResizeImage(image, 1000, 1000))
{
newImage.Save(filePath);
Interlocked.Increment(ref extractedCount);
}
}
Interlocked.Increment(ref processedCount);
int percent = (int)(processedCount / totalFiles * 100);
if (percent > previousPercent)
{
progress.Report(percent);
Interlocked.Exchange(ref previousPercent, percent);
}
});
return extractedCount;
}
public Image ResizeImage(Image image, int maxWidth, int maxHeight)
{
Image newImage = null;
if (image.Width > maxWidth || image.Height > maxHeight)
{
double widthRatio = (double)maxWidth / (double)image.Width;
double heightRatio = (double)maxHeight / (double)image.Height;
double ratio = Math.Min(widthRatio, heightRatio);
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
newImage = new Bitmap(newWidth, newHeight);
using (Graphics graphic = Graphics.FromImage(newImage))
{
graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphic.DrawImage(image, 0, 0, newWidth, newHeight);
}
}
return newImage;
}
}
【问题讨论】:
-
旁注:不要扔在平行的foreach里面来破坏。已经有中断选项。把 if 语句 CancelationTokenRequested 然后 state.Break stackoverflow.com/questions/12571048/break-parallel-foreach
-
尝试关闭进度报告;任务可能都卡在等待 UI 线程。此外,如果所有这些线程都使用磁盘 io,它们也可能会在等待磁盘访问时被卡住。
-
如果没有可靠地重现问题的a good, minimal, complete code example,就不可能说出可能发生的情况。简短的回答是,不……并发处理本身不会导致 UI 卡顿。但在某些情况下肯定有可能发生的方式。如果您需要针对特定场景的有用帮助,您需要提供一个很好的代码示例供人们使用。
-
中断而不是抛出异常更好吗?似乎有不同的建议可供使用。我最初是在做一个 state.break();
-
我关闭了报告,拖动表单时没有卡顿,但是当将鼠标悬停在按钮上时,按钮的悬停突出显示需要几秒钟。取消也需要一段时间。我会看看我可以为一个最小的完整代码示例做些什么。
标签: c# .net winforms async-await parallel.foreach