473,396 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

[Control].Invoke doesn't always return

To avoid a temporarily frozen user interface, I'm using a separate thread
to fill a list with items found in a database (there can be from a few up
to about 1000 or 1500 items).

There seems to be a problem in this: if the form containing the list is
closed before the worker thread has finished, the Invoke call used to add
entries to the list never returns.

I'm trying to avoid it in any way I can imagine, but somehow it keeps
getting stuck 100% the times the form is closed before the thread exits.

Do I need to use a critical section around all access to a control
(including closing the form), besides using Invoke to access it from a
thread?
In addition to the check for IsDisposed in the code below, I'm setting a
variable 'StopLoading' to true when the form is being closed, which makes
the thread exit as soon as it sees it; _AND_ I'm calling thread.Abort() in
the form's Closing event.
Private Delegate Sub dlg_AddLstIDEntry(ByVal Item As String)

Private Sub AddLstIDEntry(ByVal Item As String)
If Not lstID.IsDisposed Then
If lstID.InvokeRequired Then
Dim dlg As New dlg_AddLstIDEntry(AddressOf AddLstIDEntry)
lstID.Invoke(dlg, New String() {Item}) ' <<< never returns
Else
lstID.Items.Add(Item)
End If
End If
End Sub

I checked by putting a breakpoint on the first line, the sub isn't calling
itself recursively either (anyway, if it was, I would have had a stack
overflow instead of an application that won't stop).

In fact, there are three such worker threads of which more than one can be
running depending on what tabs in a form the user has visited, and when.

This is thee form's "Closing" event handler:

Private Sub frmNavigate_Closing(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing

StopLoading = True

If Not thrh_LoadID Is Nothing _
AndAlso thrh_LoadID.ThreadState = ThreadState.Running _
Then thrh_LoadID.Abort()
If Not thrh_LoadCard Is Nothing _
AndAlso thrh_LoadCard.ThreadState = ThreadState.Running _
Then thrh_LoadCard.Abort()
If Not thrh_LoadName Is Nothing _
AndAlso thrh_LoadName.ThreadState = ThreadState.Running _
Then thrh_LoadName.Abort()
End Sub
The threads are started like this:

If Not TabInitialized(0) AndAlso _
(thrh_LoadID Is Nothing _
OrElse thrh_LoadID.ThreadState <> ThreadState.Running) _
Then
lstID.Items.Clear()
thrh_LoadID = New Thread(AddressOf thr_LoadID)
thrh_LoadID.Start()
End If

They each contain a loop that scans through the result of an SQL query and
adds the items it finds to either a list or a tree through Invoke wrappers
like the one above.

Private Sub thr_LoadID()
Dim cmd As SqlClient.SqlCommand
Dim rdr As SqlClient.SqlDataReader
Dim cn2 As SqlClient.SqlConnection = CloneSQLConnection()

If Not TabInitialized(0) _
AndAlso Not cn2 Is Nothing _
AndAlso cn2.State = ConnectionState.Open Then
Try
TabInitialized(0) = True
SetTabCaption(0, "ID (loading)")
cmd = New SqlClient.SqlCommand("SELECT ID From Players", cn2)
rdr = cmd.ExecuteReader
Try
While rdr.Read And Not StopLoading
AddLstIDEntry(rdr.GetString(0))
If CurrentTab = 0 Then
Thread.Sleep(1) ' Takiteezee or UI freezes
Else
Thread.Sleep(20) ' Not current tab: slower
End If
End While
Catch ex As Exception
Debug.WriteLine(ex.ToString)
Finally
rdr.Close()
End Try
Catch ex As Exception
Debug.WriteLine(ex.ToString)
Finally
cn2.Close()
SetTabCaption(0, "ID Card")
End Try
End If
End Sub

Nov 20 '05 #1
2 2594
Hi Lucvdv,

When a thread is in sleeping status, the thread status should be
WaitSleepJoin, so when in the form closing event, the thread.abort may not
be called, and when the form is closed, the working thread is still try to
call the invoke on the main thread.
ThreadState Enumeration
http://msdn.microsoft.com/library/de...us/cpref/html/
frlrfsystemthreadingthreadstateclasstopic.asp

Here is my test code snippet, you may have a try to see if this helps you.
Dim rm As New Random
Private Sub InvokeItem()
If Me.ListBox1.InvokeRequired Then
Debug.WriteLine(Thread.CurrentThread.Name & " Invoke AddItem")
Me.Invoke(New MethodInvoker(AddressOf AddItem))
Else
Debug.WriteLine(Thread.CurrentThread.Name & " AddItem")
AddItem()
End If
End Sub
Private Sub AddItem()
Debug.WriteLine(Thread.CurrentThread.Name)
If ListBox1.Items.Count > 100 Then
ListBox1.Items.Clear()
End If
Me.ListBox1.Items.Add(rm.Next().ToString())
End Sub
Private Sub ThreadProc()
Try
While True
Thread.Sleep(1000)
InvokeItem()
End While
Catch abortException As ThreadAbortException
Debug.WriteLine(abortException.ToString())
'Do necessary cleaning job here
End Try
End Sub
Dim th As New Thread(AddressOf ThreadProc)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Thread.CurrentThread.Name = "Main Thread"
th.Name = "Working Thread"
th.Start()
End Sub

Private Sub Form1_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not th.ThreadState = System.Threading.ThreadState.Stopped Then
th.Abort()
End If
th.Join()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
InvokeItem()
Me.ListBox1.Items.Add(th.ThreadState.ToString())
End Sub

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 20 '05 #2
On Wed, 28 Jul 2004 05:53:29 GMT, v-******@online.microsoft.com ("Peter
Huang") wrote:
Hi Lucvdv,

When a thread is in sleeping status, the thread status should be
WaitSleepJoin, so when in the form closing event, the thread.abort may not
be called, and when the form is closed, the working thread is still try to
call the invoke on the main thread.


Thanks a lot: that was it.

Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Ingo Schasiepen | last post by:
Hi there, i'm evaluating if c# is suited to replace a script language. Most of the elements of this language can be replaced with a c#-library, but it also has some realtime-like elements. E.g.,...
5
by: Martin Maat [EBL] | last post by:
Hi, I have a GUI application that responds to events coming from an externaql application. In the implementing code for the event I need to create a GUI control and "parent" the control into the...
16
by: Duncan Mole | last post by:
Hi, This is probably an easy one but it iy first bit of p/invoke. I am trying to use the following C struct in a call: typedef struct { BYTE SRB_Cmd; BYTE SRB_Status, BYTE ...
2
by: VM | last post by:
How can I display the contents of a datatable in a windows datagrid while the table is being filled? Here's my summarized code: delegate void loadAuditFileToTableDelegate(); private void...
2
by: rawCoder | last post by:
Hi I am having this InvalidOperationException with message Cannot call Invoke or InvokeAsync on a control until the window handle has been created This is raised when i try to invoke a method...
14
by: stic | last post by:
Hi, I'm in a middle of writing something like 'exception handler wraper' for a set of different methodes. The case is that I have ca. 40 methods form web servicem, with different return values...
19
by: trint | last post by:
Ok, I start my thread job: Thread t = new Thread(new ThreadStart(invoicePrintingLongRunningCodeThread)); t.IsBackground = true; t.Start(); There are lots of calls to controls and many...
1
by: Kris van der Mast | last post by:
Hi, been a while since I posted a question myself instead of trying to help others out. I'm refactoring an existing web app that uses dynamic loading of user controls and a lot of...
3
by: rn5a | last post by:
The ASPX FileUpload control displays a TextBox along with a 'Browse...' Button. Setting the different properties of this control just reflects the changes in the TextBox but not the Button. For...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.