473,805 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

BackgroundWorke r thread locking UI

I have a background worker thread that scans the network listing computers
that are connected. I have a delegate that I call that invokes a procdure
that loads a dataset with computer names and then attaches it to a dropdown.
When I run it, my UI freezes until it completes. Any thoughts on how to do
this without freezing the UI?

John
Code

'General Declaration

Private Delegate Sub LoadComputerDel egate()

'called from form load

bgLoadComputers .RunWorkerAsync ()

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal e As
System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork

tsStatus.Text = "Loading Computers. Please wait..."

System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))

Invoke(New LoadComputerDel egate(AddressOf LoadComputerDro pDown))

End Sub

Private Sub LoadComputerDro pDown()

'get the computers on the domain

Try

Dim enTry As DirectoryEntry = New DirectoryEntry( LDAP://[MYDOMAIN])

Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)

mySearcher.Filt er = ("(objectClass= Computer)")

Dim resEnt As SearchResult

For Each resEnt In mySearcher.Find All

Try

Dim tmpID As String = Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)

If Mid(tmpID, 1, 2) = "L1" Then

Dim rwComputer As DataRow

rwComputer = dtComputers.New Row

rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))

dtComputers.Row s.Add(rwCompute r)

End If

tsStatus.Text = "Computers Loaded..."

cboDomainComute rs.DataSource = dtComputers

cboDomainComute rs.DisplayMembe r = "Computer Name"

Catch ex As Exception

End Try

Next

Catch ex As Exception

End Try

End Sub

Sep 19 '06 #1
3 3200
John,
You need to do the actual work in the DoWork event handler.

I would call LoadComputerDro pDown directly from DoWork, when
LoadComputerDro pDown completes I would Invoke a method on the UI that
"returns" the dataset...

Something like:

'Code
Private Delegate Sub LoadComputerDel egate(ByVal table As DataTable)

'called from form load

Protected Overrides Sub OnLoad(ByVal e As System.EventArg s)
MyBase.OnLoad(e )
tsStatus.Text = "Loading Computers. Please wait..."
bgLoadComputers .RunWorkerAsync ()
End Sub
'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal
e As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork
System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))
LoadComputerDro pDown()
End Sub

Private Sub LoadComputerDro pDown()
Dim dtComputers As New DataTable("Comp uters")
dtComputers.Col umns.Add("Compu ter Name", GetType(String) )
'get the computers on the domain
Try
Dim enTry As DirectoryEntry = New
DirectoryEntry( "LDAP://TSBRADLEY")
Dim mySearcher As DirectorySearch er = New
DirectorySearch er(enTry)
mySearcher.Filt er = ("(objectClass= Computer)")
Dim resEnt As SearchResult
For Each resEnt In mySearcher.Find All
Try
Dim tmpID As String =
Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)
If Mid(tmpID, 1, 2) = "L1" Then
Dim rwComputer As DataRow
rwComputer = dtComputers.New Row
rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))
dtComputers.Row s.Add(rwCompute r)
End If
Invoke(New LoadComputerDel egate(AddressOf
SetDomainComute rs), dtComputers)
Catch ex As Exception
Invoke(New LoadComputerDel egate(AddressOf
SetDomainComute rs), dtComputers)
End Try
Next
Catch ex As Exception
Invoke(New LoadComputerDel egate(AddressOf SetDomainComute rs),
dtComputers)
End Try
End Sub

Private Sub SetDomainComute rs(ByVal dtComputers As DataTable)
tsStatus.Text = "Computers Loaded..."
cboDomainComute rs.DataSource = dtComputers
cboDomainComute rs.DisplayMembe r = "Computer Name"
End Sub

Note: You should not refer to controls (tsStatus) from the DoWork method.
"John Wright" <ri**********@n otmail.comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
>I have a background worker thread that scans the network listing computers
that are connected. I have a delegate that I call that invokes a procdure
that loads a dataset with computer names and then attaches it to a
dropdown. When I run it, my UI freezes until it completes. Any thoughts on
how to do this without freezing the UI?

John
Code

'General Declaration

Private Delegate Sub LoadComputerDel egate()

'called from form load

bgLoadComputers .RunWorkerAsync ()

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal e
As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork

tsStatus.Text = "Loading Computers. Please wait..."

System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))

Invoke(New LoadComputerDel egate(AddressOf LoadComputerDro pDown))

End Sub

Private Sub LoadComputerDro pDown()

'get the computers on the domain

Try

Dim enTry As DirectoryEntry = New DirectoryEntry( LDAP://[MYDOMAIN])

Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)

mySearcher.Filt er = ("(objectClass= Computer)")

Dim resEnt As SearchResult

For Each resEnt In mySearcher.Find All

Try

Dim tmpID As String = Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)

If Mid(tmpID, 1, 2) = "L1" Then

Dim rwComputer As DataRow

rwComputer = dtComputers.New Row

rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))

dtComputers.Row s.Add(rwCompute r)

End If

tsStatus.Text = "Computers Loaded..."

cboDomainComute rs.DataSource = dtComputers

cboDomainComute rs.DisplayMembe r = "Computer Name"

Catch ex As Exception

End Try

Next

Catch ex As Exception

End Try

End Sub
Sep 20 '06 #2
John,
Doh! You don't need the delegate or the Invoke, the "beauty" of the
background work thread is that it handles the communication between both
threads for you.

Something like:

'called from form load

Protected Overrides Sub OnLoad(ByVal e As System.EventArg s)
MyBase.OnLoad(e )
tsStatus.Text = "Loading Computers. Please wait..."
bgLoadComputers .RunWorkerAsync ()
End Sub

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal
e As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork
System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))
e.Result = LoadComputerDro pDown()
End Sub

Private Function LoadComputerDro pDown() As DataTable
Dim dtComputers As New DataTable("Comp uters")
dtComputers.Col umns.Add("Compu ter Name", GetType(String) )
'get the computers on the domain
Dim enTry As DirectoryEntry = New DirectoryEntry( "LDAP://[MYDOMAIN])
Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)
mySearcher.Filt er = ("(objectClass= Computer)")
Dim resEnt As SearchResult
For Each resEnt In mySearcher.Find All
Dim tmpID As String =
Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)
If Mid(tmpID, 1, 2) = "L1" Then
Dim rwComputer As DataRow
rwComputer = dtComputers.New Row
rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))
dtComputers.Row s.Add(rwCompute r)
End If
Next
Return dtComputers
End Function

Private Sub bgLoadComputers _RunWorkerCompl eted(ByVal sender As Object,
ByVal e As System.Componen tModel.RunWorke rCompletedEvent Args) Handles
bgLoadComputers .RunWorkerCompl eted
If e.Error Is Nothing Then
tsStatus.Text = "Computers Loaded..."
cboDomainComute rs.DataSource = e.Result
cboDomainComute rs.DisplayMembe r = "Computer Name"
Else
MessageBox.Show (e.Error.ToStri ng(), Application.Pro ductName,
MessageBoxButto ns.OK, MessageBoxIcon. Error)
End If
End Sub
--
Hope this helps
Jay B. Harlow [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net

"John Wright" <ri**********@n otmail.comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
>I have a background worker thread that scans the network listing computers
that are connected. I have a delegate that I call that invokes a procdure
that loads a dataset with computer names and then attaches it to a
dropdown. When I run it, my UI freezes until it completes. Any thoughts on
how to do this without freezing the UI?

John
Code

'General Declaration

Private Delegate Sub LoadComputerDel egate()

'called from form load

bgLoadComputers .RunWorkerAsync ()

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal e
As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork

tsStatus.Text = "Loading Computers. Please wait..."

System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))

Invoke(New LoadComputerDel egate(AddressOf LoadComputerDro pDown))

End Sub

Private Sub LoadComputerDro pDown()

'get the computers on the domain

Try

Dim enTry As DirectoryEntry = New DirectoryEntry( LDAP://[MYDOMAIN])

Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)

mySearcher.Filt er = ("(objectClass= Computer)")

Dim resEnt As SearchResult

For Each resEnt In mySearcher.Find All

Try

Dim tmpID As String = Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)

If Mid(tmpID, 1, 2) = "L1" Then

Dim rwComputer As DataRow

rwComputer = dtComputers.New Row

rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))

dtComputers.Row s.Add(rwCompute r)

End If

tsStatus.Text = "Computers Loaded..."

cboDomainComute rs.DataSource = dtComputers

cboDomainComute rs.DisplayMembe r = "Computer Name"

Catch ex As Exception

End Try

Next

Catch ex As Exception

End Try

End Sub
Sep 20 '06 #3
Excellent. This works great. Thanks.

John
"Jay B. Harlow [MVP - Outlook]" <Ja************ @tsbradley.netw rote in
message news:CD******** *************** ***********@mic rosoft.com...
John,
Doh! You don't need the delegate or the Invoke, the "beauty" of the
background work thread is that it handles the communication between both
threads for you.

Something like:

'called from form load

Protected Overrides Sub OnLoad(ByVal e As System.EventArg s)
MyBase.OnLoad(e )
tsStatus.Text = "Loading Computers. Please wait..."
bgLoadComputers .RunWorkerAsync ()
End Sub

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal
e As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork
System.Threadin g.Thread.Sleep( TimeSpan.FromSe conds(2))
e.Result = LoadComputerDro pDown()
End Sub

Private Function LoadComputerDro pDown() As DataTable
Dim dtComputers As New DataTable("Comp uters")
dtComputers.Col umns.Add("Compu ter Name", GetType(String) )
'get the computers on the domain
Dim enTry As DirectoryEntry = New
DirectoryEntry( "LDAP://[MYDOMAIN])
Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)
mySearcher.Filt er = ("(objectClass= Computer)")
Dim resEnt As SearchResult
For Each resEnt In mySearcher.Find All
Dim tmpID As String =
Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)
If Mid(tmpID, 1, 2) = "L1" Then
Dim rwComputer As DataRow
rwComputer = dtComputers.New Row
rwComputer("Com puter Name") =
(Mid((resEnt.Ge tDirectoryEntry ().Name.ToStrin g), 4))
dtComputers.Row s.Add(rwCompute r)
End If
Next
Return dtComputers
End Function

Private Sub bgLoadComputers _RunWorkerCompl eted(ByVal sender As Object,
ByVal e As System.Componen tModel.RunWorke rCompletedEvent Args) Handles
bgLoadComputers .RunWorkerCompl eted
If e.Error Is Nothing Then
tsStatus.Text = "Computers Loaded..."
cboDomainComute rs.DataSource = e.Result
cboDomainComute rs.DisplayMembe r = "Computer Name"
Else
MessageBox.Show (e.Error.ToStri ng(), Application.Pro ductName,
MessageBoxButto ns.OK, MessageBoxIcon. Error)
End If
End Sub
--
Hope this helps
Jay B. Harlow [MVP - Outlook]
.NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net

"John Wright" <ri**********@n otmail.comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
>>I have a background worker thread that scans the network listing computers
that are connected. I have a delegate that I call that invokes a procdure
that loads a dataset with computer names and then attaches it to a
dropdown. When I run it, my UI freezes until it completes. Any thoughts
on how to do this without freezing the UI?

John
Code

'General Declaration

Private Delegate Sub LoadComputerDel egate()

'called from form load

bgLoadComputer s.RunWorkerAsyn c()

'sub that does the work

Private Sub bgLoadComputers _DoWork(ByVal sender As System.Object, ByVal e
As System.Componen tModel.DoWorkEv entArgs) Handles bgLoadComputers .DoWork

tsStatus.Tex t = "Loading Computers. Please wait..."

System.Threadi ng.Thread.Sleep (TimeSpan.FromS econds(2))

Invoke(New LoadComputerDel egate(AddressOf LoadComputerDro pDown))

End Sub

Private Sub LoadComputerDro pDown()

'get the computers on the domain

Try

Dim enTry As DirectoryEntry = New DirectoryEntry( LDAP://[MYDOMAIN])

Dim mySearcher As DirectorySearch er = New DirectorySearch er(enTry)

mySearcher.Fil ter = ("(objectClass= Computer)")

Dim resEnt As SearchResult

For Each resEnt In mySearcher.Find All

Try

Dim tmpID As String = Mid(resEnt.GetD irectoryEntry.N ame.ToString, 4)

If Mid(tmpID, 1, 2) = "L1" Then

Dim rwComputer As DataRow

rwComputer = dtComputers.New Row

rwComputer("Co mputer Name") =
(Mid((resEnt.G etDirectoryEntr y().Name.ToStri ng), 4))

dtComputers.Ro ws.Add(rwComput er)

End If

tsStatus.Tex t = "Computers Loaded..."

cboDomainComut ers.DataSource = dtComputers

cboDomainComut ers.DisplayMemb er = "Computer Name"

Catch ex As Exception

End Try

Next

Catch ex As Exception

End Try

End Sub

Sep 20 '06 #4

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

Similar topics

8
4857
by: Pieter | last post by:
Hi, I'm having some weird problem using the BackGroundWorker in an Outlook (2003) Add-In, with VB.NET 2005: I'm using the BackGroundWorker to get the info of some mailitems, and after each item I want to raise the ProgressChanged-event to update the DataGridView. It works fine when only one Progresschanged is fired, but at the second, third, fopurth etc it raises everytile a 'Cross-thread operation not valid"-exception on lmy...
2
8750
by: Sebastian Crewe | last post by:
Greetings, I was much encouraged to see the new BackgroundWorker class in .NET v2. On the face of it, much easier to use than the various delegates and events of yore, though I imagine the same base classes are being invoked. Anyway, I have given it a try with a VB.NET application that generates charts. Since there are some 3,000 charts to do, I wanted to put the chart generation on a separate thread. Works fine inasmuch as the...
5
14135
by: Rob R. Ainscough | last post by:
I'm using a BackgroundWorker to perform a file download from an ftp site. Per good code design practices where I separate my UI code from my core logic code (in this case my Download file method in my FileIO class) I've established Public Event in my core logic classes along with RaiseEvents (that will updated a progress bar on the UI side). This all works great when I'm NOT using Threading (BackgroundWorker), however, as soon as I...
9
5025
by: =?Utf-8?B?VE9NX1Bhc2FkZW5h?= | last post by:
Hello, In my ASP.Net app I'm launching a BackgroundWorker thread in my Page_Load function. In that thread I'm attempting to connect to a SQL server using this connection string "Initial Catalog=MyDB;Data Source=MyServer;Integrated Security=True;". When I use the same connection string in my main thread of execution it works fine. However when I use that connection string in the newly created thread I get this exception: "Login...
5
11238
by: redear | last post by:
Is there a way to immediately terminate a BackgroundWorker thread? My problem is that the BackgroundWorker starts with a call to My.Computer.FileSystem.GetFiles that can run for a very long time if it is pointing to a directory tree with many files. If the user requests cancellation during this time, the main thread can call CancelAsync and can post a "Cancellation Pending" message to the user, but the BackgroundWorker cannot respond to...
8
16584
by: =?Utf-8?B?cmFuZHkxMjAw?= | last post by:
I have an application with several BackgroundWorker threads. I hoped I'd be able to just type backgroundworker1.Name = "bw1"; but I don't see a name property. Any thoughts on how to name a backgroundworker thread? Thanks, Randy
9
18036
by: RvGrah | last post by:
I'm completely new to using background threading, though I have downloaded and run through several samples and understood how they worked. My question is: I have an app whose primary form will almost always lead to the user opening a certain child window that's fairly resource intensive to load. Is it possible to load this form in a backgroundworker and then use the Show method and hide method as necessary? Anyone know of
5
11724
by: =?Utf-8?B?RWl0YW4=?= | last post by:
Hello, I need to create a background thread and two (or more) options are available to me: 1. BackgroundWorker 2. Asynch delegate method and BeginInvoke What are the differences between them in performance, complexity etc.
4
2585
by: Sin Jeong-hun | last post by:
This is what I've always been wondered. Suppose I've created a class named Agent, and the Agent does some lengthy job. Of course I don't want to block the main window, so the Agent does the job in a separate thread. If the job is progressed it fires an event, and the main window handled the event by changing the value of a progress bar. The problem is that this event is fired in another thread so when the handler in the main window tries...
2
11873
by: =?Utf-8?B?SGFycnkgS2Vjaw==?= | last post by:
I have introduced a component to my solution that is throwing an exception about needing to be run in single threaded apartment mode. This component is created in an async call by a BackgroundWorker object, which seems to be on a MTA thread. Is there a way for me to get the BackgroundWorker thread to run in STA mode, or do I have to remove the BackgroundWorker and hand spin my own async call?
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10613
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10107
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.