Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Populating a listview from another thread
- 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);
- }
- }
- }
- 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();
- }
- using System;
- using System.Windows.Forms;
- namespace TestWinFormsThreding
- {
- class TestFormCotrolHelper
- {
- delegate void UniversalVoidDelegate();
- ///
- /// Call form controll action from different thread
- ///
- 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"));
- }
- //...
- }
- }
- private delegate void MyDelegate(string s);
- public void UpdateControl(Control targetControl, string text)
- {
- if (targetControl.InvokeRequired)
- {
- // THIS IS STILL THE IN THE CONTEXT OF THE THREAD
- MyDelegate call = new MyDelegate(UpdateControl);
- targetControl.Invoke(call, new object[] { text });
- }
- else
- {
- // do control stuff
- // THIS IS IN THE CONTEXT OF THE UI THREAD
- }
- }
- Action action = new Action(() =>
- {
- // Add item to list view here
- });
- if (_ListVireRef.InvokeRequired)
- {
- _ListVireRef.BeginInvoke(action); // or Invoke if wanting to call synchronously.
- }
- else
- {
- action();
- }
Add Comment
Please, Sign In to add comment