listView的跨线程问题 [英] Cross-Threading issue with listView
本文介绍了listView的跨线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好,在每个帖子重复之前,我告诉您我看过所有其他帖子,即时消息仍然丢失了一些使用代理或后台工作人员等信息...但是我如何确保此线程的安全性,我想删除文件它自己的线程.
OK before everyone post duplicate let me inform you I have looked at all those other post and im still lost some say use delegates or background worker etc... but how would I make this thread safe i want to delete the files on its own thread.
这是我正在使用的代码.
here is the code that i am working with.
private void button1_Click(object sender, EventArgs e)
{
cleanFiles.RunWorkerAsync();
}
private void cleanFiles_DoWork(object sender, DoWorkEventArgs e)
{
if (listView1.CheckedItems.Count != 0)
{
// If so, loop through all checked files and delete.
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
string tempDirectory = Path.GetTempPath();
foreach (ListViewItem item in listView1.CheckedItems)
{
string fileName = item.Text;
string filePath = Path.Combine(tempDirectory, fileName);
try
{
File.Delete(filePath);
}
catch (Exception)
{
//ignore files being in use
}
}
}
PaintListView(tFile);
MessageBox.Show("Files removed");
toolStripStatusLabel1.Text = ("Ready");
}
else
{
MessageBox.Show("Please put a check by the files you want to delete");
}
}
推荐答案
如Reed所述,您不能从UI线程本身以外的线程访问UI元素.因此,您必须传递一个委托 Control.Invoke()
来与UI线程一起执行,就像这样
As Reed mentioned, you cannot access UI elements from a thread other than the UI thread itself. So, you'll have to pass on a delegate Control.Invoke()
to be executed with the UI Thread, like this
尝试
private void cleanFiles_DoWork(object sender, DoWorkEventArgs e)
{
if (listView1.CheckedItems.Count != 0)
{
// If so, loop through all checked files and delete.
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
string tempDirectory = Path.GetTempPath();
foreach (ListViewItem item in listView1.CheckedItems)
{
string fileName = item.Text;
string filePath = Path.Combine(tempDirectory, fileName);
try
{
File.Delete(filePath);
}
catch (Exception)
{
//ignore files being in use
}
}
}
PaintListViewAndSetLabel();
}
else
{
ShowMessageBox();
}
}
private void ShowMessageBox()
{
if(InvokeRequired)
{
this.Invoke(new Action(ShowMessageBox), new object[0]);
return;
}
MessageBox.Show("Please put a check by the files you want to delete");
}
private void PaintListViewAndSetLabel()
{
if (InvokeRequired)
{
this.Invoke(new Action(PaintListViewAndSetLabel),new object[0]);
return;
}
PaintListView(tFile);
MessageBox.Show("Files removed");
toolStripStatusLabel1.Text = ("Ready");
}
这篇关于listView的跨线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文