[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 411
  • Last Modified:

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?
Thanks
lifeform23
0
lifeform23
Asked:
lifeform23
  • 2
1 Solution
 
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

    Application.DoEvents()

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.

~IM
0
 
KarcOriginCommented:
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()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        '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
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    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.SuspendLayout()
        '
        'Button1
        '
        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"
        '
        'Button2
        '
        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"
        '
        'Label1
        '
        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"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 12)
        Me.ClientSize = New System.Drawing.Size(340, 116)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    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
            WorkerThread.Abort()
            Label1.Text = "Calculation aborted"
            Label1.Refresh()
        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)
        WorkerThread.Start()

    End Sub

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

    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.
Cheers!
0
 
GohdanTheMoblinCommented:
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
        Label1.Refresh()
        Application.DoEvents()
    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
            UpdateLabel(i.ToString())
        Next
    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 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWindowsFormsControlClassInvokeRequiredTopic.asp for details.
   
0
 
KarcOriginCommented:
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!!

Cheers!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now