thorpedosg

9YCzJ1Mv

Aug 6th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. Populating a listview from another thread
  2. class CheckBlankPages
  3. {
  4.  
  5. public String[] pdfFiles
  6. { get; set; }
  7.  
  8. ListView _ListVireRef;
  9. public int NrCRT = 1;
  10.  
  11.  
  12. public CheckBlankPages(String[] pdfFiles = null, ListView listView = null)
  13. {
  14. this.pdfFiles = pdfFiles;
  15. _ListVireRef = listView;
  16.  
  17. }
  18. public void StartCheckingPDF()
  19. {
  20. foreach (string pdf in pdfFiles)
  21. {
  22. String[] itm = { (NrCRT++).ToString(), pdf };
  23. ListViewItem item = new ListViewItem(itm);
  24. _ListVireRef.Items.Add(item);
  25. }
  26. }
  27. }
  28.  
  29. DialogResult rezultat = openFileDialog1.ShowDialog();
  30. if (rezultat == DialogResult.OK)
  31. {
  32.  
  33. CheckBlankPages ck = new CheckBlankPages(openFileDialog1.FileNames, listView1);
  34. Thread CheckPDFs = new Thread(new ThreadStart(ck.StartCheckingPDF));
  35. CheckPDFs.Start();
  36. }
  37.  
  38. using System;
  39. using System.Windows.Forms;
  40.  
  41. namespace TestWinFormsThreding
  42. {
  43. class TestFormCotrolHelper
  44. {
  45. delegate void UniversalVoidDelegate();
  46.  
  47. ///
  48. /// Call form controll action from different thread
  49. ///
  50. public static void ControlInvike(Control control, Action function)
  51. {
  52. if (control.IsDisposed || control.Disposing)
  53. return;
  54.  
  55. if (control.InvokeRequired)
  56. {
  57. control.Invoke(new UniversalVoidDelegate(() => ControlInvike(control, function)));
  58. return;
  59. }
  60. function();
  61. }
  62. }
  63.  
  64. public partial class TestMainForm : Form
  65. {
  66. // ...
  67. // This will be called from thread not the same as MainForm thread
  68. private void TestFunction()
  69. {
  70. TestFormCotrolHelper.ControlInvike(listView1, () => listView1.Items.Add("Test"));
  71. }
  72. //...
  73. }
  74. }
  75.  
  76. private delegate void MyDelegate(string s);
  77.  
  78. public void UpdateControl(Control targetControl, string text)
  79. {
  80. if (targetControl.InvokeRequired)
  81. {
  82. // THIS IS STILL THE IN THE CONTEXT OF THE THREAD
  83. MyDelegate call = new MyDelegate(UpdateControl);
  84. targetControl.Invoke(call, new object[] { text });
  85. }
  86. else
  87. {
  88. // do control stuff
  89. // THIS IS IN THE CONTEXT OF THE UI THREAD
  90. }
  91. }
  92.  
  93. Action action = new Action(() =>
  94. {
  95. // Add item to list view here
  96. });
  97. if (_ListVireRef.InvokeRequired)
  98. {
  99. _ListVireRef.BeginInvoke(action); // or Invoke if wanting to call synchronously.
  100. }
  101. else
  102. {
  103. action();
  104. }
Add Comment
Please, Sign In to add comment