从另一个线程填充一个ListView [英] Populating a listview from another thread
本文介绍了从另一个线程填充一个ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想填充从另一个类列表视图,但我歌厅此错误:
跨线程操作无效:控制'ListView1的从比它创建线程以外的线程访问。在
I'm trying to populate a listview from another class, but I'm geting this error: " Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on. "
在我的课堂我宣布我的列表视图是这样的:
In my class I declare my listview like this:
class CheckBlankPages
{
public String[] pdfFiles
{ get; set; }
ListView _ListVireRef;
public int NrCRT = 1;
public CheckBlankPages(String[] pdfFiles = null, ListView listView = null)
{
this.pdfFiles = pdfFiles;
_ListVireRef = listView;
}
public void StartCheckingPDF()
{
foreach (string pdf in pdfFiles)
{
String[] itm = { (NrCRT++).ToString(), pdf };
ListViewItem item = new ListViewItem(itm);
_ListVireRef.Items.Add(item);
}
}
}
在我的MainForm我用这段代码:
and in my MainForm I use this code:
DialogResult rezultat = openFileDialog1.ShowDialog();
if (rezultat == DialogResult.OK)
{
CheckBlankPages ck = new CheckBlankPages(openFileDialog1.FileNames, listView1);
Thread CheckPDFs = new Thread(new ThreadStart(ck.StartCheckingPDF));
CheckPDFs.Start();
}
什么是错的?
What is wrong?
推荐答案
通常我做的是这样的:
using System;
using System.Windows.Forms;
namespace TestWinFormsThreding
{
class TestFormCotrolHelper
{
delegate void UniversalVoidDelegate();
/// <summary>
/// Call form controll action from different thread
/// </summary>
public static void ControlInvike(Control control, Action function)
{
if (control.IsDisposed || control.Disposing)
return;
if (control.InvokeRequired)
{
control.Invoke(new UniversalVoidDelegate(() => ControlInvike(control, function)));
return;
}
function();
}
}
public partial class TestMainForm : Form
{
// ...
// This will be called from thread not the same as MainForm thread
private void TestFunction()
{
TestFormCotrolHelper.ControlInvike(listView1, () => listView1.Items.Add("Test"));
}
//...
}
}
这篇关于从另一个线程填充一个ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文