Xan*_*rUu 2 .net c# multithreading winforms
我正在尝试从另一个类填充列表视图,但我发现这个错误:"跨线程操作无效:控制'listView1'从其创建的线程以外的线程访问."
在我的班级中,我声明我的列表视图是这样的:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的MainForm中我使用此代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
怎么了?
小智 6
通常我这样做:
using System;
using System.Windows.Forms;
namespace TestWinFormsThreding
{
class TestFormControlHelper
{
delegate void UniversalVoidDelegate();
/// <summary>
/// Call form control action from different thread
/// </summary>
public static void ControlInvoke(Control control, Action function)
{
if (control.IsDisposed || control.Disposing)
return;
if (control.InvokeRequired)
{
control.Invoke(new UniversalVoidDelegate(() => ControlInvoke(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.ControlInvoke(listView1, () => listView1.Items.Add("Test"));
}
//...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8342 次 |
| 最近记录: |