Add handler in runtime within a constructor VB.NET - vb.net

REEDIT
I have reedited the question to be more understandable following the advices of #enigmativity in his comments.
This is an example of what I want to do in my program. I tried to make it as simple as I can, so I hope you can understand my question.
The problem is the following: I am trying to add handlers dynamically, because I have an object which needs to fire a handler when something happens on it, and I can create this objects dynamically in the program. Maybe following this example you could understand my problem.
If I have an object, for example, a car, with its own properties (doors, wheels, motor..), and something happen in the road, I want the handler BREAK fires, and in the BREAK function do whatever I need to make it break. Here is the example code of the class for this object:
Public Class Car
Public Property carName As String
Public Property wheels As Integer
Public Property motor As String
Public Property color As String
Public Property speed As Decimal
Private Event BreakCar()
Public Sub New()
End Sub
Public Sub New(ByVal name_ As String, ByVal wheels_ As Integer, motor As String, color As String, ByVal speed As Decimal)
carName = name_
wheels = wheels_
motor = motor_
color = color_
speed = speed_
End Sub
Public Sub Break()
Try
AddHandler BreakCar, AddressOf EmergencyBreak
RaiseEvent AutoMsg()
Catch ex As Exception
MsgBox("Error: " & ex.Message & ". Stacktrace: " & ex.StackTrace)
End Try
End Sub
Private Sub EmergencyBreak()
Try
MsgBox("Emergency Break")
Catch ex As Exception
MsgBox("Error: " & ex.Message & ". Stacktrace: " & ex.StackTrace)
End Try
End Sub
End Class
Also, in the main form I have something like this:
Public Class frmMain
...
Private Sub AddMe(ByVal name_ As String, ByVal wheels_ As Integer, ByVal motor_ As String, ByVal color_ As String, ByVal speed_ As Decimal, Byval initCoordinates_ as PointLatLng)
Try
unitsList.Add(New Car(name_, wheels_, motor_, color_, speed_))
Dim marker As GMapMarker
marker = New GMarkerGoogle(initCoordinates_, GMarkerGoogleType.orange_dot)
marker.ToolTipMode = MarkerTooltipMode.Always
marker.ToolTipText = name_
meOverlay.Markers.Add(marker)
Dim lvItem As ListViewItem
lvItem = lvUnits.Items.Add(name_)
lvItem.SubItems.Add(Math.Round(initCoordinates_.Lat, 4))
lvItem.SubItems.Add(Math.Round(initCoordinates_.Lng, 4))
Dim unit_ As Car = unitsList.FirstOrDefault(Function(x) x.carName = name_)
unit_.Break()
Dim tTemp_ As Thread = New Thread(Sub() CarMovement(unit_))
tTemp_.Name = name_
tTemp_.Priority = ThreadPriority.Normal
tTemp_.Start()
unitsThreadList.Add(tTemp_)
Catch ex As Exception
MsgBox("Error: " & ex.Message & ". Stacktrace: " & ex.StackTrace)
End Try
End Sub
...
End Class
With this, I am trying to add cars in the system, using a different thread to each one, and after adding the car to the system, start its handler to make it BREAK when some condition happens.
My problem is that the handler never fires, and I don't know the reasons because when something happens to the car X, the handler Break() must fires but it doesn't.
Am I doing something wrong? Maybe it is not possible to add handlers to each object created dynamically like this?
Thanks for any help!

Related

global variable defined in winforms not working as expected

I have a project in VB.Net that requires a global variable (a list of event log objects) throughout. This seemed simple enough, just define the variable and initialize in the Application's StartUp event, then access it throughout the application. Unfortunately, this only seems to work when there are no child processes (they have no access to the global variable) - so I'm way over my head as how to access the global variable from the child worker processes (if that is even possible).
The program starts several Test worker processes (that check multiple DB connections from different sources, remote web services from several sources, network checks, etc) w/ progress bars for each. If an error occurs during any of these tests, the error needs to be logged.
The problem is that, the program cannot log events to the Windows Event system because it won't be running under an administrator account (so logging there is not possible thanks to MS's decision to prevent logging under normal user accounts w/Vista,7,8,10), the program also can't log to a text file due to it being asynchronous and the file access contention problems (immediately logging an event to a text file won't work), so I wish to log any events/errors in memory (global variable), THEN dump it to a log file AFTER all child processes complete. Make any sense?
I created a class called AppEvent
Public Class AppEvent
Sub New()
EventTime_ = Date.Now
Level_ = EventLevel.Information
Description_ = String.Empty
Source_ = String.Empty
End Sub
Private EventTime_ As Date
Public Property EventTime() As Date
Get
Return EventTime_
End Get
Set(ByVal value As Date)
EventTime_ = value
End Set
End Property
Private Level_ As EventLevel
Public Property Level() As EventLevel
Get
Return Level_
End Get
Set(ByVal value As EventLevel)
Level_ = value
End Set
End Property
Private Description_ As String
Public Property Description() As String
Get
Return Description_
End Get
Set(ByVal value As String)
Description_ = value
End Set
End Property
Private Source_ As String
Public Property Source() As String
Get
Return Source_
End Get
Set(ByVal value As String)
Source_ = value
End Set
End Property
End Class
Public Enum EventLevel
[Information]
[Warning]
[Error]
[Critical]
[Fatal]
End Enum
And create a public variable just for this (and add an initial event to the AppEvents list)
Namespace My
Partial Friend Class MyApplication
'global variable here (using this for logging asynch call errors, then dumping this into a log file when all asynch calls are complete (due to file contention of log file)
Public AppEvents As New List(Of AppEvent)
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
'create first event and add it to the global variable declared above
AppEvents.Add(New AppEvent With {.EventTime = Now, .Description = "Program Started", .Level = EventLevel.Information, .Source = "QBI"})
End Sub
End Class
End Namespace
Next, in my logging class, I have some methods for logging, flushing/writing the event(s)
Public Class AppLogging
Public Shared Sub WriteEventToAppLog(evt As AppEvent)
LogDataToFile(FormatLineItem(evt.EventTime, evt.Level, evt.Description, evt.Source))
End Sub
Public Shared Sub WriteEventsToAppLog(AppEvents As List(Of AppEvent))
Dim sbEvents As New StringBuilder
If AppEvents.Count > 0 Then
For Each evt In AppEvents
sbEvents.AppendLine(FormatLineItem(evt.EventTime, evt.Level, evt.Description, evt.Source))
Next
LogDataToFile(sbEvents.ToString.TrimEnd(Environment.NewLine))
End If
End Sub
Private Shared Function FormatLineItem(eventTime As Date, eventLevel As EventLevel, eventDescr As String, eventSource As String) As String
Return String.Format("Logged On: {0} | Level: {1} | Details: {2} | Source: {3}", eventTime, System.Enum.GetName(GetType(EventLevel), eventLevel).Replace("[", "").Replace("]", ""), eventDescr, eventSource)
End Function
Private Shared Sub LogDataToFile(eventLogText As String, Optional ByVal LogFileName As String = "Error.log", Optional ByVal HeaderLine As String = "****** Application Log ******")
'log file operations
Dim LogPath As String = System.AppDomain.CurrentDomain.BaseDirectory()
If Not LogPath.EndsWith("\") Then LogPath &= "\"
LogPath &= LogFileName
Dim fm As FileMode
Try
If System.IO.File.Exists(LogPath) Then
fm = FileMode.Append
Else
fm = FileMode.Create
eventLogText = HeaderLine & Environment.NewLine & eventLogText
End If
Using fs As New FileStream(LogPath, fm, FileAccess.Write)
Using sw As New StreamWriter(fs)
sw.WriteLine(eventLogText)
End Using
End Using
My.Application.AppEvents.Clear() 'clears the global var
Catch ex As Exception
'handle this
End Try
End Sub
Public Shared Sub WriteEventToMemory(eventLevel As EventLevel, eventDescription As String, Optional eventSource As String = "")
Dim evt As New AppEvent
evt.Description = eventDescription
evt.Level = eventLevel
evt.EventTime = Now
evt.Source = eventSource
Try
My.Application.AppEvents.Add(evt)
Catch ex As Exception
Throw
End Try
End Sub
Public Shared Sub FlushEventsToLogFile()
WriteEventsToAppLog(My.Application.AppEvents)
End Sub
End Class
There's a few methods in here, but the method called in every exception handler is WriteEventToMemory (it merely adds an AppEvent to the AppEvents list).
An example test routine/worker process (to the local database) looks like:
#Region "local db test"
Private Sub TestLocalDBWorkerProcess_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles TestLocalDBWorkerProcess.DoWork
Me.TestLocalDBStatusMessage = TestLocalDB()
End Sub
Private Sub TestLocalDBWorkerProcess_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles TestLocalDBWorkerProcess.RunWorkerCompleted
Me.prgLocalDatabase.Style = ProgressBarStyle.Blocks
Me.prgLocalDatabase.Value = 100
If Me.ForcedCancelTestLocalDB Then
Me.lbStatus.Items.Add("Local DB Test Cancelled.")
Else
If TestLocalDBStatusMessage.Length > 0 Then
Me.lblLocalDatabaseStatus.Text = "Fail"
Me.lbStatus.Items.Add(TestLocalDBStatusMessage)
SendMessage(Me.prgLocalDatabase.Handle, 1040, 2, 0) 'changes color to red
Else
Me.lblLocalDatabaseStatus.Text = "OK"
Me.lbStatus.Items.Add("Connection to local database is good.")
Me.prgLocalDatabase.ForeColor = Color.Green
End If
End If
Me.ForcedCancelTestLocalDB = False
Me.TestLocalDBProcessing = False
ProcessesFinished()
End Sub
Private Sub StartTestLocalDB()
Me.prgLocalDatabase.Value = 0
Me.prgLocalDatabase.ForeColor = Color.FromKnownColor(KnownColor.Highlight)
Me.prgLocalDatabase.Style = ProgressBarStyle.Marquee
Me.TestLocalDBProcessing = True
Me.TestLocalDBStatusMessage = String.Empty
Me.lblLocalDatabaseStatus.Text = String.Empty
TestLocalDBWorkerProcess = New System.ComponentModel.BackgroundWorker
With TestLocalDBWorkerProcess
.WorkerReportsProgress = True
.WorkerSupportsCancellation = True
.RunWorkerAsync()
End With
End Sub
Private Function TestLocalDB() As String
Dim Statusmessage As String = String.Empty
Try
If Me.TestLocalDBWorkerProcess.CancellationPending Then
Exit Try
End If
If Not QBData.DB.TestConnection(My.Settings.DBConnStr3) Then
Throw New Exception("Unable to connect to local database!")
End If
Catch ex As Exception
Statusmessage = ex.Message
AppLogging.WriteEventToMemory(EventLevel.Fatal, ex.Message, "TestLocalDB")
End Try
Return Statusmessage
End Function
#End Region
The try-catch block simply catches the exception and writes it to memory (I just wrapped it in the WriteEventToMemory method, but it's just adding it to the AppEvents list: My.Application.AppEvents.Add(evt)
Everything appeared to be working peachy, until I noticed that the count for AppEvents was (1) after the Startup event, then it's count was (0) from any of the child processes, finally, the count was (1) when the list was dumped to the error log file (only the first event added was there). It is clearly acting like there are multiple versions of the AppEvents variable.
****** Application Log ******
Logged On: 10/7/2016 6:01:45 PM | Level: Information | Details: Program Started | Source: QBI
Only the first event shows up, the other events not (they are added, there's no null ref exceptions or any exceptions - like phantoms). Any event added to the global variable on the MAIN thread stays (and gets logged, ultimately). So this is clearly a multithreaded issue (never tried this before in a Windows app).
Any ideas on how to remedy?
As mentioned above, I had to pass the events back to the calling workerprocess, so, in the main form I put in:
Private AppEvent_TestLocalDB As New AppEvent
In the DoWork (for each process), I changed it to:
Private Sub TestLocalDBWorkerProcess_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles TestLocalDBWorkerProcess.DoWork
Me.TestLocalDBStatusMessage = TestLocalDB(AppEvent_TestLocalDB)
End Sub
The TestLocalDB sub now looks like:
Private Function TestLocalDB(ByRef aEvent As AppEvent) As String
Dim Statusmessage As String = String.Empty
Try
If Me.TestLocalDBWorkerProcess.CancellationPending Then
Exit Try
End If
If Not QBData.DB.TestConnection(My.Settings.DBConnStr3) Then
Throw New Exception("Unable to connect to local database!")
End If
Catch ex As Exception
Statusmessage = ex.Message
With aEvent
.Description = ex.Message
.Level = EventLevel.Fatal
.Source = "TestLocalDB"
End With
End Try
Return Statusmessage
End Function
Note there is no error logging, just the event variable (ByRef to pass it back, the equivalent to C# out).
When the worker process completes, I add the following:
With AppEvent_TestLocalDB
AppLogging.WriteEventToMemory(.Level, .Description, .Source)
End With
(the other worker processes work the same way)
When ALL the processes are complete, then I flush it to the log file.
AppLogging.FlushEventsToLogFile()
Now the custom event/error log entries look like so (with a freshly made file):
****** Application Log ******
Logged On: 10/7/2016 10:14:36 PM | Level: Information | Details: Program Started | Source: QBI
Logged On: 10/7/2016 10:14:53 PM | Level: Fatal | Details: Unable to connect to local database! | Source: TestLocalDB
That was it - just pass the variable back to the caller

Accesing a class with properties from another class returns null values

I am making an application that reads values from a meter that is connected to my computer via a serial cable. When i press a button i send a command to the meter and after a few miliseconds i get a response back from the meter with the answer.
I am saving these values to a class that has properties init, so that i can access these values from anywhere.
So my problem is that when i try to get the values back it returns a 'nothing value', and its probably from the initialization i have that has a 'New' like this'Dim clsSavedValues As New clsSavedValues', so when i try to get the values from that property class i create a new instanse and that instanse is empty if am not mistaken.
Ill post the code below but here is how the code flows:
I have 3 classes. MainClass, ProtocolClass, PropertiesClass.
From main i call a method inside ProtocolClass, and that method sends a command to the meter. after a few miliseconds i get a call back inside ProtocolClass anf this method is called 'Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived' and it saves that return value to the PropertiesClass.
And after the DataReceived method is finished i go back to the MainClass and call another method to get the values from the PropertiesClass that i just saved but they return null. I know they are saved correctly because i can access them if i call them from within the ProtocolClass. But they are null from MainClass.
Here is my code:
MainClass
'Here i call the ProtocolClass
Private Sub btnGetLastTransaction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetLastTransaction.Click
clsProtocol.GetLastTransaction(1, Integer.Parse(tbxTransactionPosition.Text))
End Sub
'Here i try to read the valies from PropertiesClass
Public Sub RetrieveMeterSerialNumber()
Dim clsSavedValues As New clsSavedValues
lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber
End Sub
ProtocolClass
Public Sub GetLastTransaction(ByVal destinationAddress As String, ByVal transactionNum As Integer)
clsSavedValues = New clsSavedValues 'Creating Instance of the properties class
Try
Dim v_bodyOfMessage As [Byte]() = {ASCIItoHEX("G"), _
ASCIItoHEX("r")}
Dim v_bytearray As [Byte]() = ConstructCommand(v_bodyOfMessage)
SendCommand(v_bytearray)
Catch ex As Exception
Console.WriteLine("Meter serial number button click exception: {0}", ex)
End Try
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
If comOpen Then
Try
ReDim rx(rxPacketSize)
Console.WriteLine("RESPONSE")
For i = 0 To rxPacketSize - 1
readByte = SerialPort.ReadByte.ToString
Console.WriteLine(i.ToString & ": " & Conversion.Int(readByte).ToString)
rx(i) = Conversion.Int(readByte).ToString
If i <> 0 Then
If Convert.ToByte(rx(i)) = vDelimeterFlag(0) Then Exit For
End If
Next
DecodeResponse()
Catch ex As Exception
MsgBox("SerialPort_DataReceived Exception: " & ex.Message)
End Try
End If
End Sub
Private Sub GetMeterSerialNumber()
Dim i_startPosition As Integer = 5
Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition)
clsSavedValues.SaveMeterSerialNumber = meterSerialNumber
frmExplorer.RetrieveMeterSerialNumber() 'This is the call to the main class
End Sub
PropertiesClass
Public Property SaveMeterSerialNumber() As String
Get
Return _MeterSerialNumber
End Get
Set(ByVal meterSerialNumber As String)
_MeterSerialNumber = meterSerialNumber
End Set
End Property
I want to get the values from the PropertiesClass because ill get more than wan response from the meter and that causes thread issues and i cannot keep track with them. So i save the values in one class and then i want to access them all from that class.
Sorry for the long post, ask me anything you want for clarification
clsSavedValues in SerialPort_DataReceived() and in your Main Class RetrieveMeterSerialNumber() are two different objects (with same variable names but each 'new' create a new instance of clsSavedValues ) maybe you should pass the clsSavedValues var from protocol to Main as parameter.
Main :
Public Sub RetrieveMeterSerialNumber(clsSavedValues As clsSavedValues )
lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber
End Sub
Protocol :
Private Sub GetMeterSerialNumber()
Dim i_startPosition As Integer = 5
Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition)
clsSavedValues.SaveMeterSerialNumber = meterSerialNumber
frmExplorer.RetrieveMeterSerialNumber(clsSavedValues) 'This is the call to the main class
End Sub
or use a static property in your PropertiesClass

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

When to expect a `Cross-thread Exception`?

I'm having a hard time trying to understand what seems to be a random throwing of cross-thread exceptions.
Examples
When invoked in a different thread, why does this work:
Dim text As String = Me.Text
While this will throw an exception:
Me.Text = "str"
What makes it even stranger is that the following do work:
Dim text As String = Me.ctl.Margin.ToString() : Me.ctl.Margin = New Padding(1, 2, 3, 4)
Dim text As String = Me.ctl.MyProp : Me.MyProp = "str"
Note
Yes, I know that I could just invoke the property like this:
Me.Invoke(Sub() Me.Text = "str")
Question
So when can I expect a cross-thread exception?
Code
This is the code i used to test the Me.Text property:
Public Class Form1
Public Sub New()
Me.InitializeComponent()
Me.ctl = New Control()
Me.ctl.Text = "test_control"
Me.Controls.Add(Me.ctl)
End Sub
Private Sub TestGet(sender As Object, e As EventArgs) Handles Button1.Click
Dim t As New Thread(AddressOf Me._Proc)
t.Start(TESTTYPE.GET)
End Sub
Private Sub TestSet(sender As Object, e As EventArgs) Handles Button2.Click
Dim t As New Thread(AddressOf Me._Proc)
t.Start(TESTTYPE.SET)
End Sub
Private Sub _Proc(tt As TESTTYPE)
Dim text As String = String.Empty
Dim [error] As Exception = Nothing
Try
If (tt = TESTTYPE.GET) Then
text = Me.ctl.Text
ElseIf (tt = TESTTYPE.SET) Then
Me.ctl.Text = "test"
End If
Catch ex As Exception
[error] = ex
End Try
Me.Invoke(Sub() Me._Completed(tt, text, [error]))
End Sub
Private Sub _Completed(tt As TESTTYPE, text As String, ByVal [error] As Exception)
If ([error] Is Nothing) Then
If (tt = TESTTYPE.GET) Then
MessageBox.Show(String.Concat("Success: '", text, "'"), tt.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information)
ElseIf (tt = TESTTYPE.SET) Then
MessageBox.Show("Success", tt.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else
MessageBox.Show([error].Message, tt.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private ReadOnly ctl As Control
Private Enum TESTTYPE
[GET] = 0
[SET] = 1
End Enum
End Class
Edit
This will not throw an exception:
Public Event TestChanged As EventHandler
Public Property Test() As String
Get
Return Me.m_test
End Get
Set(value As String)
If (value <> Me.m_test) Then
Me.m_test = value
Me.Invalidate()
RaiseEvent TestChanged(Me, EventArgs.Empty)
End If
End Set
End Property
the main time a cross-thread exception occurs when you do something that would cause an event to fire from the non-UI thread that affects the UI thread; So reading a property can be fine, but writing the property of a control would cause it to repaint (at the very least), hence the exception.
Of course, other vendors may have used the exception for other scenarios where it is not safe to access from a different thread
So when can I expect a cross-thread exception?
Well, GUI in .Net are created in STA which means that only the thread that create the control can update it this has to do with Thread-safe concept. for this reasons when you start another thread and try to access the control which is owned by the main thread you will get an invalidOperationException
So when can I expect a cross-thread exception?
Really simple, when you access some function or property of a control, from a thread which do not have right to access it.
For example, in Window form application when you try to access the button placed on form from a non-ui thread, i.e. not the main thread, (and you have not set any flags manually to allow cross-thread operation)
EDIT As per comment, how can I know I can/can not access a getter/ setter of a property. Where are the access rights defined? you can always be on safe side by querying the control's InvokeRequired property in Windows
Okay, so I did some research myself, and it turns out that the exception originates in the .Handle property of the Control.
<Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DispId(-515), SRDescription("ControlHandleDescr")> _
Public ReadOnly Property Handle As IntPtr
Get
If ((Control.checkForIllegalCrossThreadCalls AndAlso Not Control.inCrossThreadSafeCall) AndAlso Me.InvokeRequired) Then
Throw New InvalidOperationException(SR.GetString("IllegalCrossThreadCall", New Object() {Me.Name}))
End If
If Not Me.IsHandleCreated Then
Me.CreateHandle()
End If
Return Me.HandleInternal
End Get
End Property
System.Windows.Forms.resources:
IllegalCrossThreadCall=Cross-thread operation not valid: Control '{0}' accessed from a thread other than the thread it was created on.
So I believe the answer would be something like this:
Whenever the handle of a control is invoked from a different thread.
(I'll give you all a vote up as all the answers are relevant towards cross-threading.)
The following code will throw an exception:
Public Class Form1
Private Sub Test(sender As Object, e As EventArgs) Handles Button1.Click
Dim t As New Thread(AddressOf Me._Proc)
t.Start()
End Sub
Private Sub _Proc(id As Integer)
Dim [error] As Exception = Nothing
Try
Dim p As IntPtr = Me.Handle
Catch ex As Exception
[error] = ex
End Try
Me.Invoke(Sub() Me._Completed([error]))
End Sub
Private Sub _Completed(ByVal [error] As Exception)
If ([error] Is Nothing) Then
MessageBox.Show("Success", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show([error].Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.tbDescription.Text = [error].Message
End If
End Sub
End Class

Form is not updating, after custom class event is fired

I'm having an issue where my main form isn't updating even though I see the event fire off. Let me explain the situation and share some of my code which I'm sure will be horrible since I'm an amateur.
I created a class to take in the settings for running a process in the background. I add some custom events in that class so I could use that in my form instead of a timer.
I put a break on the two subs for that handle those events and I see them get kicked off as soon as an install starts.
I look at the data and it's coming across and no exceptions are thrown.
At first I thought it was because the datagridview had some latency issues. I set that to be double buffered through some tricks I found but it didn't matter. There was still a roughly 10 second delay before the data showed up in the datagrid.
I thought about it and decided I really didn't need a datagridview and replaced the control with a multiline textbox, but it didn't make a difference. It's still taking 10 seconds or longer to show updates to the form/textbox.
I've included some of my code below.
Public Shared WithEvents np As NewProcess
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
np = New NewProcess
AddHandler np.InstallFinished, AddressOf np_InstallFinished
AddHandler np.InstallStarted, AddressOf np_InstallStarted
Catch ex As Exception
End Try
End Sub
Protected Sub np_InstallFinished(ByVal Description As String, ByVal ExitCode As Integer)
InstallInProcess = False
If Not Description = Nothing Then
If Not ExitCode = Nothing Then
AddLog(String.Format("Completed install of {0} ({1}).", Description, ExitCode))
Else
AddLog(String.Format("Completed install of {0}.", Description))
End If
End If
RefreshButtons()
UpdateListofApps()
np.Dispose()
End Sub
Protected Sub np_InstallStarted(ByVal Description As String)
InstallInProcess = True
If Not Description = Nothing Then AddLog(String.Format("Started the install of {0}.", Description))
End Sub
Public Class NewProcess
Dim ProcessName As String
Dim ProcessVisibile As Boolean
Dim Arguments As String
Dim WaitforExit As Boolean
Dim Description As String
Dim ShellExecute As Boolean
Dim EC As Integer = Nothing 'Exit Code
Private IsBusy As Boolean = Nothing
Dim th As Threading.Thread
Public Event InstallFinished(ByVal Description As String, ByVal ExitCode As Integer)
Public Event InstallStarted(ByVal Description As String)
Public Function Busy() As Boolean
If IsBusy = Nothing Then Return False
Return IsBusy
End Function
Public Function ExitCode() As Integer
Return EC
End Function
Public Function ProcessDescription() As String
Return Description
End Function
''' <summary>
''' Starts a new multithreaded process.
''' </summary>
''' <param name="path">Path of the File to run</param>
''' <param name="Visible">Should application be visible?</param>
''' <param name="Arg">Arguments</param>
''' <param name="WaitforExit">Wait for application to exit?</param>
''' <param name="Description">Description that will show up in logs</param>
''' <remarks>Starts a new multithreaded process.</remarks>
Public Sub StartProcess(ByVal path As String, ByVal Visible As Boolean, Optional ByVal Arg As String = Nothing, Optional ByVal WaitforExit As Boolean = False, Optional ByVal Description As String = Nothing)
Try
Me.ProcessName = path
Me.ProcessVisibile = Visible
If Arguments = Nothing Then Me.Arguments = Arg
Me.Description = Description
Me.WaitforExit = WaitforExit
If IsBusy And WaitforExit Then
MessageBox.Show("Another install is already in process, please wait for previous install to finish.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Sub
End If
If Not fn_FileExists(ProcessName) Then
MessageBox.Show("Could not find file " & ProcessName & ".", "Could not start process because file is missing.", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
th = New Threading.Thread(AddressOf NewThread)
With th
.IsBackground = True
If Not Description Is Nothing Then .Name = Description
.Start()
End With
Catch ex As Exception
End Try
End Sub
Private Sub NewThread()
Dim p As Process
Try
p = New Process
With p
.EnableRaisingEvents = True
.StartInfo.Arguments = Arguments
.StartInfo.FileName = ProcessName
.StartInfo.CreateNoWindow = ProcessVisibile
End With
If ProcessVisibile Then
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal
Else
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
End If
p.Start()
IsBusy = True
RaiseEvent InstallStarted(Description)
If WaitforExit Then
Do While p.HasExited = False
Threading.Thread.Sleep(500)
Loop
IsBusy = False
RaiseEvent InstallFinished(Description, p.ExitCode)
End If
EC = p.ExitCode
Catch ex As Exception
End Try
End Sub
Public Sub Dispose()
ProcessName = Nothing
ProcessVisibile = Nothing
Arguments = Nothing
WaitforExit = Nothing
Description = Nothing
EC = Nothing
InstallInProcess = Nothing
th.Join()
MemoryManagement.FlushMemory()
End Sub
End Class
Sub AddLog(ByVal s As String)
Try
s = String.Format("[{0}] {1}", TimeOfDay.ToShortTimeString, s)
Form1.tbLogs.AppendText(s & vbCrLf)
Using st As New StreamWriter(LogFilePath, True)
st.WriteLine(s)
st.Flush()
End Using
Catch ex As Exception
End Try
End Sub
Any idea's? I'm at a complete loss.
I've tried adding application.doevents, me.refresh and quite a few other things :(
Form1.tbLogs.AppendText(s & vbCrLf)
Standard VB.NET trap. Form1 is a class name, not a reference to the form. Unfortunately, VB.NET implemented an anachronism from VB6 where that was legal. It however falls apart when you use threads. You'll get another form object automatically created, one that isn't visible because its Show() method was never called. Otherwise dead as a doornail since the thread is not pumping a message loop.
You'll need to pass a reference to the actual form object that the user is looking at to the worker class. The value of Me in the Form1 code. You will also have to use Control.Invoke since it isn't legal to update controls from another thread. I recommend you fire an event instead, one that Form1 can subscribe to, so that your worker class isn't infected with implementation details of the UI.
Some suggestions:
First make it work without threads. (Ironical you call yourself an amateur, It so happened I only learned to do that after I was past the 'amateur' stage)
Don't try to update the GUI Controls from a background thread. That's forbidden in windows. I'm not sure that's what you do (no VB guru), but it sure looks like it.
Use the .net BackgroundWorker class. It has builtin functionality to talk back to the main thread from a background thread. It's not perfect but a good start.
You got me pointed in the right direction. Thanks Hans. This was my solution:
Private Sub SetText(ByVal [text] As String)
If Me.tbLogs.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.tbLogs.Text = [text]
End If
End Sub
Private Sub np_InstallStarted(ByVal Description As String)
InstallInProcess = True
If Me.tbLogs.Text = "" Then
SetText(String.Format("[{0}] Started the install of {1}.{2}", TimeOfDay.ToShortTimeString, Description, vbCrLf))
Else
SetText(tbLogs.Text & vbCrLf & String.Format("[{0}] Started the install of {1}.{2}", TimeOfDay.ToShortTimeString, Description, vbCrLf))
End If
End Sub
Private Sub np_InstallFinished(ByVal [Description] As String, ByVal [ExitCode] As Integer)
InstallInProcess = False
If Not Description = Nothing Then
If Not ExitCode = Nothing Then
SetText(tbLogs.Text & vbCrLf & String.Format("[{0}] Completed install of {1} ({2}).{3}", TimeOfDay.ToShortTimeString, Description, ExitCode, vbCrLf))
Else
SetText(tbLogs.Text & vbCrLf & String.Format("[{0}] Completed install of {1}.{3}", TimeOfDay.ToShortTimeString, Description, vbCrLf))
End If
End If
RefreshButtons()
UpdateListofApps()
np.Dispose()
End Sub
So when the event kicks off that the install has started or finished, I use the SetText to update the log on the original form.
Problem is I posted that original post as an "unregistered user" so now I'm trying to figure out a way to say the question was answered. Thanks again for your help!