how to interrupt program operations with user events

Posted on 2004-11-16
Last Modified: 2010-04-24
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?
Question by:lifeform23
    LVL 85

    Accepted Solution

    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.

    LVL 5

    Expert Comment

    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.
    LVL 2

    Expert Comment

    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.
    LVL 5

    Expert Comment

    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!!


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
    Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now