我知道从服务器下载电子邮件时速度很慢。但是当运行程序并从硬盘读取/加载消息时,有什么方法可以让它更快吗?
在构造函数中,我启动了一个后台工作者
DirectoryInfo di = new DirectoryInfo(emailsDirectory);
files = di.GetFiles();
if (files.Length > 0)
{
backgroundWorker2.RunWorkerAsync();
}
然后在dowork事件中
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
int counter = 0;
MimekitallLoadedMessages = new List<MimeKit.MimeMessage>();
MimeKit.MimeMessage loadedMessage = null;
DirectoryInfo di = new DirectoryInfo(emailsDirectory);
FileInfo[] files = di.GetFiles();
for (int i = 0; i < files.Length; i++)
{
string uid = seenUids[0];
loadedMessage = MimeKit.MimeMessage.Load(files[i].FullName);
MimekitallLoadedMessages.Add(loadedMessage);
downloaded.Add(seenUids[i]);
counter += 1;
int nProgress = counter * 100 / files.Length;
backgroundWorker2.ReportProgress(nProgress);
}
}
然后是我更新progressBar pbt1和listView(ListViewCostumControl.lvnf)的progresschanged事件
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbt1.Value = e.ProgressPercentage;
pbt1.Text = e.ProgressPercentage.ToString() + "%";
pbt1.Invalidate();
ListViewCostumControl.lvnf.Items.Add(new ListViewItem(new string[]
{
MimekitallLoadedMessages[countUploadMsg].From.ToString(), //From Column
MimekitallLoadedMessages[countUploadMsg].Subject, //Subject Column
MimekitallLoadedMessages[countUploadMsg].Date.ToString() //Date Column
}));
countUploadMsg += 1;
}
这是 pbt1 的类部分,也许这让它变慢了?没有把握
public class ProgressBarWithText : ProgressBar
{
const int WmPaint = 15;
SizeF TextSize;
PointF TextPos;
bool dontpaint = false;
public ProgressBarWithText()
{
this.DoubleBuffered = true;
this.TextChanged += ProgressBarWithText_TextChanged;
this.SizeChanged += ProgressBarWithText_SizeChanged;
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
void RecalcTextPos()
{
if (this.IsDisposed == true)
return;
if (string.IsNullOrEmpty(base.Text))
return;
using (var graphics = Graphics.FromHwnd(this.Handle))
{
TextSize = graphics.MeasureString(base.Text, this.Font);
TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
}
}
void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
void ProgressBarWithText_TextChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (dontpaint == false)
{
switch (m.Msg)
{
case WmPaint:
using (var graphics = Graphics.FromHwnd(Handle))
graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);
break;
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams result = base.CreateParams;
result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return result;
}
}
}
从硬盘加载消息的整个过程似乎很慢。我读取/加载的硬盘上的文件是 eml 类型,有些文件大小为 8 KB,有些文件大小为 380 KB,一个是 4 MB