473,379 Members | 1,174 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,379 software developers and data experts.

Immediate Termination of a BackgroundWorker Thread

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 the CancellationPending
property until the call to My.Computer.FileSystem.GetFiles returns. It
seems inelegant to rewrite the call to My.Computer.FileSystem.GetFiles
to use calls to Dir or something that would allow me to poll the
CancellationPending property while I'm building the collection of file
names. And I have not wanted to rewrite the BackgroundWorker as a
standard thread (read that "go through the learning curve"!). I would
rather abort the BackgroundWorker thread but do not see how to do it.

Thanks.

redear
Feb 28 '07 #1
5 11145
On Feb 27, 7:37 pm, redear <red...@nowhere.com.invalidwrote:
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 the CancellationPending
property until the call to My.Computer.FileSystem.GetFiles returns. It
seems inelegant to rewrite the call to My.Computer.FileSystem.GetFiles
to use calls to Dir or something that would allow me to poll the
CancellationPending property while I'm building the collection of file
names. And I have not wanted to rewrite the BackgroundWorker as a
standard thread (read that "go through the learning curve"!). I would
rather abort the BackgroundWorker thread but do not see how to do it.

Thanks.

redear

If it's running in a seperate background thread, why do you need it to
terminate immediately? After all what the user doesn't see can't hurt
them (well, sorta :-) )

Thanks,

Seth Rowe

Feb 28 '07 #2
redear wrote:
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 the CancellationPending
property until the call to My.Computer.FileSystem.GetFiles returns.
<snip>

You may try using Thread.Abort, which will cause an exception to be
thrown in the thread that you want to finish. You must call
Thread.ResetAbort in you Catch or Finally block, or else the exception
will bubble up...

A few words of caution, though: thread synchronization is almost an
art, and maybe you start getting more troubles than the one you want
to solve, such as bad breath, too much sugar in your coffee or strange
calls to your cell phone at 3 a.m. ...

<code>
'At file level:
Imports SysThread = System.Threading
Imports SysComps = System.ComponentModel

'...
'At form level:
Private mThread As SysThread.Thread

Private Sub BGWorker_DoWork( _
ByVal Sender As Object, _
ByVal E As SysComps.DoWorkEventArgs _
) Handles BGWorker.DoWork

mThread = SysThread.Thread.CurrentThread
Try
For X As Integer = 0 To 100
SysThread.Thread.Sleep(1000)
BGWorker.ReportProgress(X)
Next
Catch Ex As SysThread.ThreadAbortException
SysThread.Thread.ResetAbort()
End Try
End Sub

Private Sub BTNCancel_Click( _
ByVal Sender As Object, _
ByVal E As System.EventArgs _
) Handles BTNCancel.Click

If BGWorker.IsBusy AndAlso _
mThread IsNot Nothing Then
mThread.Abort()
mThread = Nothing
End If
End Sub
</code>
In the code above, BGWorker is the background worker component, and
BTNCancel is, as you may have guessed, a "cancel" button.

HTH.

Regards,

Branco.

Feb 28 '07 #3
On 28 Feb 2007 05:23:47 -0800, "Branco Medeiros"
<br*************@gmail.comwrote:
>redear wrote:
>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 the CancellationPending
property until the call to My.Computer.FileSystem.GetFiles returns.
<snip>

You may try using Thread.Abort, which will cause an exception to be
thrown in the thread that you want to finish. You must call
Thread.ResetAbort in you Catch or Finally block, or else the exception
will bubble up...

A few words of caution, though: thread synchronization is almost an
art, and maybe you start getting more troubles than the one you want
to solve, such as bad breath, too much sugar in your coffee or strange
calls to your cell phone at 3 a.m. ...

<code>
'At file level:
Imports SysThread = System.Threading
Imports SysComps = System.ComponentModel

'...
'At form level:
Private mThread As SysThread.Thread

Private Sub BGWorker_DoWork( _
ByVal Sender As Object, _
ByVal E As SysComps.DoWorkEventArgs _
) Handles BGWorker.DoWork

mThread = SysThread.Thread.CurrentThread
Try
For X As Integer = 0 To 100
SysThread.Thread.Sleep(1000)
BGWorker.ReportProgress(X)
Next
Catch Ex As SysThread.ThreadAbortException
SysThread.Thread.ResetAbort()
End Try
End Sub

Private Sub BTNCancel_Click( _
ByVal Sender As Object, _
ByVal E As System.EventArgs _
) Handles BTNCancel.Click

If BGWorker.IsBusy AndAlso _
mThread IsNot Nothing Then
mThread.Abort()
mThread = Nothing
End If
End Sub
</code>
In the code above, BGWorker is the background worker component, and
BTNCancel is, as you may have guessed, a "cancel" button.

HTH.

Regards,

Branco.
Branco,

Thanks for the clear example as well as the words of warning. Very
helpful!

redear
Feb 28 '07 #4
TP
I recommend you use FindFirstFile/FindNextFile/FindClose via
pinvoke. That way you could periodically check for a pending
cancel and then exit.

For example, execute FindNextFile in a loop for 100 iterations,
and then check for a pending cancel. If there is a pending cancel
do a FindClose and exit the loop.

-TP

redear wrote:
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 the CancellationPending
property until the call to My.Computer.FileSystem.GetFiles returns. It
seems inelegant to rewrite the call to My.Computer.FileSystem.GetFiles
to use calls to Dir or something that would allow me to poll the
CancellationPending property while I'm building the collection of file
names. And I have not wanted to rewrite the BackgroundWorker as a
standard thread (read that "go through the learning curve"!). I would
rather abort the BackgroundWorker thread but do not see how to do it.

Thanks.

redear
Feb 28 '07 #5
On Wed, 28 Feb 2007 13:08:38 -0500, "TP"
<tp***************@mailandnews.comwrote:
>I recommend you use FindFirstFile/FindNextFile/FindClose via
pinvoke. That way you could periodically check for a pending
cancel and then exit.

For example, execute FindNextFile in a loop for 100 iterations,
and then check for a pending cancel. If there is a pending cancel
do a FindClose and exit the loop.

-TP
TP,

Thanks. That's what I am going to do. Looks like it is better practice
than aborting a thread from the thread pool, even if it is a few more
statements.

Thanks.

redear
Feb 28 '07 #6

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

Similar topics

2
by: dm1608 | last post by:
Hi -- I have a C# application that basically has a button that executes a SQL Reader to loop thru a rather large resul set. Thru each interation of the reader object, I check to see if a file...
2
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...
5
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...
9
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...
8
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...
9
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...
5
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...
4
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...
2
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.