[VB.NET][C#] Multi-thread / Crossthreading Example

Someone was asking how to do multi-threading in the shoutbox and my original example didn’t work because of cross-threads. This basically means I couldn’t set the value of a control within a thread since it’s considered a different process. Well I did manage to get it to work and I figured I’d post the code here. I will also include the source code both both the VB.net and C# versions below.

VB

  1. Imports System.Threading
  2. Public Class Form1
  3.  
  4. Dim Max As Double = 600000
  5. Dim i As Integer = 0
  6. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  7. ProgressBar1.Maximum = Max
  8. Dim threadFill As Thread = New Thread(AddressOf Thread_FillProgressbar)
  9. threadFill.Start()
  10. End Sub
  11.  
  12. Private Sub Thread_FillProgressbar()
  13.  
  14. For i = 0 To Max
  15. AccessControl()
  16. Next
  17. End Sub
  18.  
  19. Private Sub AccessControl()
  20. If Me.InvokeRequired Then
  21. Me.Invoke(New MethodInvoker(AddressOf AccessControl))
  22. Else
  23.  
  24. ProgressBar1.Value = i
  25. ShowInTaskbar = True
  26. End If
  27. End Sub
  28. End Class

C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Threading;
  10. namespace CSharp_multithreading
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18.  
  19. int Max = 60000;
  20. int i = 0;
  21. private void Form1_Load(object sender, EventArgs e)
  22. {
  23. progressBar1.Maximum = Max;
  24. Thread threadFill = new Thread(Thread_FillProgressBar);
  25. threadFill.Start();
  26. }
  27.  
  28. private void Thread_FillProgressBar()
  29. {
  30. for (i = 0; i <= Max; i++)
  31. {
  32. accessControl();
  33. }
  34. }
  35.  
  36. private void accessControl()
  37. {
  38. if (InvokeRequired)
  39. {
  40.  
  41. Invoke(new MethodInvoker(accessControl));
  42.  
  43. }
  44. else
  45. {
  46. progressBar1.Value = i;
  47. ShowInTaskbar = true;
  48.  
  49. }
  50.  
  51. }
  52. }
  53. }

VB.NET Source

C# Source

Leave a Reply

Your email address will not be published. Required fields are marked *