Running a thread on demand

callraheel

Well-known member
Joined
Dec 12, 2004
Messages
65
Location
London,UK
Programming Experience
1-3
hello

I want to save the data entries through a thread so that while the data is being saved by that thread the data entry operator can enter the next record.

i have created a separator procedure to do that and linked it like this :

VB.NET:
[size=2][color=#0000ff]Public[/color][/size][size=2][color=#0000ff]Class[/color][/size][size=2] frmNewCollegeEntry
 
[/size][size=2][color=#0000ff]Inherits[/color][/size][size=2] System.Windows.Forms.Form
 
[/size][size=2][color=#008000]' create a private thread to handle the saving of form...
 
[/color][/size][size=2][color=#0000ff]Dim[/color][/size][size=2] objSaveThread [/size][size=2][color=#0000ff]As[/color][/size][size=2][color=#0000ff]New[/color][/size][size=2] Thread([/size][size=2][color=#0000ff]AddressOf[/color][/size][size=2] _doSaveTransaction)[/size]
 
Here goes the sub code :
[size=2][/size][size=2][color=#0000ff]Private[/color][/size][size=2] [/size][size=2][color=#0000ff]Sub[/color][/size][size=2] _doSaveTransaction()

[/size][size=2][color=#008000]' disable form and enable Cancel button...

[/color][/size][size=2][/size][size=2][color=#0000ff]Me[/color][/size][size=2].Enabled = [/size][size=2][color=#0000ff]False

[/color][/size][size=2]btnCancel.Enabled = [/size][size=2][color=#0000ff]True

[/color][/size][size=2][/size][size=2][color=#0000ff]Dim[/color][/size][size=2] infQry [/size][size=2][color=#0000ff]As[/color][/size][size=2] [/size][size=2][color=#0000ff]String[/color][/size][size=2] = "INSERT INTO st_info(SID,RollNo,ClassID,Section,AdmissionDate,Shift,Name,FName," & _

"FStatus,FOccupation,PhoneOffice,PhoneRes,PhoneNeighbour," & _

"FOffAddr,FWorkNature,ResAddr,LastSchoolCollege,SSCYear,SSCRNo,SSCMarksObt,SSCMarksMax," & _

"SSCDiv,SSCBoard," & _

"HSSCYear,HSSCRNo,HSSCMarksObt,HSSCMarksMax," & _

"HSSCDiv,HSSCBoard,CombID,EnrolNoSSC," & _

"EnrolNoFAFSc,Reference,GamesSports,Hobbies," & _

"Distinction,DisciplineReport,EntryDate,LastUpdated)"

infQry &= " VALUES('" & txtSID.Text & "'," & txtRollNo.Text & "," & Security.GetIDFromString(cmbClass.SelectedItem) & ",'" & cmbSection.SelectedItem & "'," & _GetAdmissionDate() & ",'" & _

cmbShift.SelectedItem & "','" & txtName.Text & "','" & txtFName.Text & "','" & _

_GetFatherLifeStatus() & "','" & txtFOccupation.Text & "','" & txtPhoneOff.Text & "','" & txtPhoneRes.Text & "','" & txtPhoneNeighbour.Text & "','" & _

txtBusinessAddr.Text & "','" & txtBusinessNature.Text & "','" & txtResAddress.Text & "','" & txtLastSchoolCollege.Text & "'," & txtSSCYear.Text & ",'" & txtSSCRollNo.Text & "'," & _

txtSSCMarksObt.Text & "," & txtSSCMaxMarks.Text & ",'" & txtSSCDiv.Text & "','" & _

txtSSCBoard.Text & "'," & txtHSSCYear.Text & ",'" & txtHSSCRollNo.Text & "'," & _

txtHSSCMarksObt.Text & "," & txtHSSCMaxMarks.Text & ",'" & txtHSSCDiv.Text & "','" & _

txtHSSCBoard.Text & "'," & Security.GetIDFromString(cmbCombinations.SelectedItem) & ",'" & _

txtSSCEnrolNo.Text & "','" & txtFAFScEnrolNo.Text & "','" & _

txtReference.Text & "','" & txtGames.Text & "','" & _

txtHobbies.Text & "','" & txtDistinction.Text & "','" & _

txtDisciplineReport.Text & "',NOW(),NOW());"

Console.WriteLine(infQry)

[/size][size=2][color=#0000ff]Dim[/color][/size][size=2] myConnection [/size][size=2][color=#0000ff]As[/color][/size][size=2] [/size][size=2][color=#0000ff]New[/color][/size][size=2] MySqlConnection

myConnection = Connection.AutoConnect

[/size][size=2][color=#0000ff]Dim[/color][/size][size=2] myCommand [/size][size=2][color=#0000ff]As[/color][/size][size=2] MySqlCommand = myConnection.CreateCommand()

[/size][size=2][color=#0000ff]Dim[/color][/size][size=2] myTrans [/size][size=2][color=#0000ff]As[/color][/size][size=2] MySqlTransaction

[/size][size=2][color=#008000]' Start a local transaction

[/color][/size][size=2]myTrans = myConnection.BeginTransaction()

[/size][size=2][color=#008000]' Must assign both transaction object and connection

[/color][/size][size=2][/size][size=2][color=#008000]' to Command object for a pending local transaction

[/color][/size][size=2]myCommand.Connection = myConnection

myCommand.Transaction = myTrans

[/size][size=2][color=#0000ff]Try

[/color][/size][size=2]myCommand.CommandText = infQry

myCommand.ExecuteNonQuery()

notifyIconEx1.ShowBalloon("Record Saving in Progress", "Saving Record implemented...Now saving photo", NETXP.Components.NotifyInfoFlags.Info, 3000)

[/size][size=2][color=#008000]' now design a query for inserting photo

[/color][/size][size=2][/size][size=2][color=#0000ff]Dim[/color][/size][size=2] photo() [/size][size=2][color=#0000ff]As[/color][/size][size=2] [/size][size=2][color=#0000ff]Byte[/color][/size][size=2] = GetPhoto()

myCommand.CommandText = "INSERT INTO photos(PhotoID,Photo,PhotoSize) VALUES(?PhotoID,?Photo,?PhotoSize)"

myCommand.Parameters.Add("?PhotoID", txtSID.Text)

myCommand.Parameters.Add("?Photo", photo)

myCommand.Parameters.Add("?PhotoSize", _GetPhotoLength)

myCommand.ExecuteNonQuery()

myTrans.Commit()

[/size][size=2][color=#0000ff]Me[/color][/size][size=2].notifyIconEx1.ShowBalloon("Record Saved Successfully", "Information as well as photo has been saved", NETXP.Components.NotifyInfoFlags.Info, 3000)

[/size][size=2][color=#008000]' now perform post-record-saving functions

[/color][/size][size=2]_doPostRecordSaveActions() ' two line code.....dont bother

[/size][size=2][color=#0000ff]Catch[/color][/size][size=2] ex [/size][size=2][color=#0000ff]As[/color][/size][size=2] Exception

[/size][size=2][color=#0000ff]Try

[/color][/size][size=2]myTrans.Rollback()

[/size][size=2][color=#0000ff]Me[/color][/size][size=2].notifyIconEx1.ShowBalloon("Roll Backed!", "Record roll backed successfully from database...Previous/Current Entry was not made to database", NETXP.Components.NotifyInfoFlags.Info, 3000)

[/size][size=2][color=#0000ff]Catch[/color][/size][size=2] ex1 [/size][size=2][color=#0000ff]As[/color][/size][size=2] MySqlException

[/size][size=2][color=#0000ff]If[/color][/size][size=2] [/size][size=2][color=#0000ff]Not[/color][/size][size=2] myTrans.Connection [/size][size=2][color=#0000ff]Is[/color][/size][size=2] [/size][size=2][color=#0000ff]Nothing[/color][/size][size=2] [/size][size=2][color=#0000ff]Then

[/color][/size][size=2][/size][size=2][color=#0000ff]Me[/color][/size][size=2].notifyIconEx1.ShowBalloon("ROLLBACK Error Occured", "An exception of type " & ex1.GetType().ToString() & _

" was encountered while attempting to roll back the transaction.", NotifyInfoFlags.Error, 3000)

[/size][size=2][color=#0000ff]End[/color][/size][size=2] [/size][size=2][color=#0000ff]If

[/color][/size][size=2][/size][size=2][color=#0000ff]End[/color][/size][size=2] [/size][size=2][color=#0000ff]Try

[/color][/size][size=2][/size][size=2][color=#0000ff]Me[/color][/size][size=2].notifyIconEx1.ShowBalloon("COMMIT Error Occured", "An exception of type " & ex.GetType.ToString & _

" was encountered while inserting the data." & vbCrLf & "Neither record was written to database.", NotifyInfoFlags.Error, 3000)

[/size][size=2][color=#0000ff]Finally

[/color][/size][size=2]myConnection.Close()

[/size][size=2][color=#0000ff]Me[/color][/size][size=2].Enabled = [/size][size=2][color=#0000ff]True

[/color][/size][size=2][/size][size=2][color=#0000ff]End[/color][/size][size=2] [/size][size=2][color=#0000ff]Try

[/color][/size][size=2][/size][size=2][color=#0000ff]End[/color][/size][size=2] [/size][size=2][color=#0000ff] Sub[/color][/size]
[size=2][color=#0000ff][/color][/size] 
[size=2][color=#0000ff] 
[/color][/size]

First time this thread works fine and then after that it says the following :
System.Threading.ThreadStateException: Thread is running or terminated; it can not restart.
at System.Threading.Thread.StartInternal(IPrincipal principal, StackCrawlMark& stackMark)
at System.Threading.Thread.Start()
at SIS.frmNewCollegeEntry.btnSave_Click(Object sender, EventArgs e) in D:\Projects\SIS\frmNewCollegeEntry.vb:line 1824
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at NETXP.Controls.XPButton.OnMouseUp(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)

Now can you please explain whats the problem......
My requirement is :
Until the user exits the main application this thread should work...


Regards
Raheel
 
Last edited by a moderator:
The problem doesn't seem to be with the code that the thread runs, it's probably the code used to run the thread.
Are you reinstantiating the thread variable each time you run it?
 
Well i do the following............


'create a private thread to handle the saving of form...

Dim objSaveThread AsNew Thread(AddressOf _doSaveTransaction)

' as i stated before

' now when the save button is clicked then the this code is executed
objSaveThread.Start()

Also before starting the thread i disable the whole form and enable the Cancel Button
and when that button is pressed the following code is executed
objSaveThread.Abort()

Regards
 
System.Threading.ThreadStateException: Thread is running or terminated; it can not restart.
That means exactly what it says, you can't restart a thread once it has been stopped. In my first post I mentioned reinstantiating the thread variable. That means to create a new instance of the thread. Placing the variable declaration in your button's click event handler should resolve you problem.
 
Ok thats fine,,,,, i need to know one more thing....Now as the thread will be initiated in the Save Button Click Event so what about the Cancel Button...When i click it that thread should be aborted!
I need to know how to refer the save thread from cancel button?
 
Declare a class level variable for the thread (outside of any methods). Then in your start button's click event handler create a new instance of the thread class.
VB.NET:
Private objSaveThread As System.Threading.Thread

Private Sub cmdSave_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles cmdSave.Click
    cmdSave.Enabled = False
    cmdCancel.Enabled = True
    objSaveThread = New System.Threading.Thread(AddressOf _doSaveTransaction)
    objSaveThread.IsBackground = True
    objSaveThread.Start()
End Sub

Private Sub cmdCancel_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles cmdCancel.Click
    cmdCancel.Enabled = False
    cmdSave.Enabled = True
    If objSaveThread.IsAlive Then
        objSaveThread.Abort()
    End If
End Sub
 
Back
Top