how to interrupt program operations with user events

Hi folks
I have written a VB.NET program which does long calculations. When it is working it does not respond to mouse clicks. How can I make it respond to a button click to stop it from operating?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonMiddle School Assistant TeacherCommented:
Two ways:

1) Place your long calculation in a seperate thread.

2) In your calculation loop place a call to


This will allow your app to remain responsive.  Create a boolean flag variable and check this value in your loop.  When the "Stop" button is pressed, set the flag to true.  Now in the loop, if the flag becomes true, drop out of the calc loop.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Try this:

Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()

        'This call is required by the Windows Form Designer.

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.Button1.Location = New System.Drawing.Point(176, 68)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(132, 28)
        Me.Button1.TabIndex = 1
        Me.Button1.Text = "Button1"
        Me.Button2.Location = New System.Drawing.Point(34, 68)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(132, 26)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "Button2"
        Me.Label1.Location = New System.Drawing.Point(32, 30)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(274, 26)
        Me.Label1.TabIndex = 4
        Me.Label1.Text = "Label1"
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 12)
        Me.ClientSize = New System.Drawing.Size(340, 116)
        Me.Name = "Form1"
        Me.Text = "Form1"

    End Sub

#End Region

    Dim WorkerThread As Threading.Thread

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If (WorkerThread.ThreadState = ThreadState.Running) Then
            Label1.Text = "Calculation aborted"
        End If

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        WorkerThread = New Thread(AddressOf StartCal)

    End Sub

    Private Sub StartCal()
        Dim i As Integer
        For i = 0 To 1111
            Label1.Text = CStr(i)

    End Sub

End Class

In my comment I have placed 2 command buttons and a label to show the status of the loop. You can place your calculation logic instead of my dummy loop. I hope it works.
Shame, shame, KarcOrigin, you're accessing controls created on the UI thread from the worker thread! ;)  This is a violation of a fundamental rule of Windows threading.  .NET lets it slide on by, but it can cause mysterious and hard to trace bugs, particularly on non-XP systems.

To properly work with a control from another thread, you have to use delegates to marshall the call to the UI thread.  There's 3 steps to doing this:

1.  Declare a delegate type
2.  Implement a function that matches the delegate's signature and accesses the control.
3.  Use the Control.Invoke method to marshall the function call to the thread the control was created on.

Here's an example of what to do to properly set the label text from the worker thread:

    'Step 1: Declare delegate
    Private Delegate Sub UpdateLabelDelegate(ByVal message As String)

    'Step 2: Declare sub that implements the functionality and matches the delegate's signature
    Private Sub UpdateLabelSub(ByVal message As String)
        Label1.Text = message
    End Sub

Now, alter the StartCal() sub like so to correctly work with the control:

    Private Sub StartCal()
        Dim i as Integer
        Dim UpdateLabel As New UpdateLabelDelegate(AddressOf UpdateLabelSub)
        For i = 0 to 1111
    End Sub

If you don't believe me, put the delegate and sub in, leave StartCal() alone,  and alter UpdateLabelSub by adding this to the top:
    If Label1.InvokeRequired
        MessageBox.Show("Wrong thread")
    End If

You'll see the message box, informing you that to access the control a delegate must be invoked.

See for details.
Dear GohdanTheMoblin,

I am aware of what you have mention in your comment. If you look at my code I have assign this block of code (StartCal) to a new thread and start its execution. I think you know that the AddressOf operator creates a delegate object to the StartCal method. A delegate within VB.NET is a type-safe, object-oriented function pointer. I didn't do what you have done coz I wanted to keep my code simple. Should I be shamed on it!!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.