473,729 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Call the dispose method on a different thread if an exception is thrown

Hello Group,

I am running an operation in a different thread. There are resources that
are released when the thread is done running. This is done at the end of the
execution as it raises an event, and then the operation handling this event
calls threaded object's dispose method.
The problem is: If an exception is thrown the event is never raised, the
operation never executes dispose and my resources get stuck on the memory
until the app is finally closed and then, just then, the finalize method
will call the dispose method.
How can I know if an exception was thrown in a different thread? I need that
to be able to call the dispose method myself and not wait until finalize
runs whenever it feels like.

Thanks in advance for all the replies,

Giovanni Bassi
Nov 20 '05 #1
3 1959
On 2003-10-15, Giovanni Bassi <gb****@coair.c om> wrote:
Hello Group,

I am running an operation in a different thread. There are resources that
are released when the thread is done running. This is done at the end of the
execution as it raises an event, and then the operation handling this event
calls threaded object's dispose method.
The problem is: If an exception is thrown the event is never raised, the
operation never executes dispose and my resources get stuck on the memory
until the app is finally closed and then, just then, the finalize method
will call the dispose method.
How can I know if an exception was thrown in a different thread? I need that
to be able to call the dispose method myself and not wait until finalize
runs whenever it feels like.

Thanks in advance for all the replies,

Giovanni Bassi


I think you may want to check into Try-Catch-Finally... The finally
block is always executed - even if an exception is thrown. I'm not
exactly sure with out seeing some code of course, but I would guess this
is a code structure issue. Is there any way you can post a scaled down
snippet of code that illustrates what you are trying to accomplish?

--
Tom Shelton
MVP [Visual Basic]
Nov 20 '05 #2
Hey Tom,

Thanks for the Reply.
Here is what is some code:
This runs on a menu click handler:

Dim objReports As Reports
objReports = New ExcelPayrollCD( strFullFileName ,
g_objTables.Con nection, intSerial)
AddHandler objReports.Repo rtFinished, AddressOf
objReports_Repo rtFinished

Dim objNewThreadSta rt As New Threading.Threa dStart(AddressO f
objReports.Gene rate)
Dim objNewThread As New Threading.Threa d(objNewThreadS tart)
objNewThread.St art()

And there is this sub to handle the above code:

Private Sub objReports_Repo rtFinished(ByVa l sender As Excel.Reports)

Dim Result As Excel.ReportRes ults
Result = sender.ReportRe sult

Dim objNewThreadSta rt As New Threading.Threa dStart(AddressO f
CType(sender, IDisposable).Di spose)
Dim objNewThread As New Threading.Threa d(objNewThreadS tart)
objNewThread.St art()

Select Case Result
Case Excel.ReportRes ults.OK
MessageBox.Show ("Report created!" & vbNewLine &
sender.FullFile Name & " saved.", "Payroll CD", MessageBoxButto ns.OK,
MessageBoxIcon. Information, MessageBoxDefau ltButton.Button 1)
Case Excel.ReportRes ults.Cancelled
MessageBox.Show ("Report cancelled.")
Case Excel.ReportRes ults.Connection TimeOut
MessageBox.Show ("Connection Timed Out.")
Case Excel.ReportRes ults.DataNotRet rived
MessageBox.Show ("Data Not Retrived.")
Case Excel.ReportRes ults.ReportMode lNotFound
MessageBox.Show ("Report model not found.")
Case Excel.ReportRes ults.UnknownErr or
MessageBox.Show ("Unkown Error.")
Case Else

End Select

End Sub
I want to catch an error on objReports.Gene rate, which is run at
objNewThread.St art.
Normally, without MultiThreading, I'd simply do:

Try
objReports.Gene rate()
Catch
'do whatever
Finally
objReports.Disp ose
End Try

but I can't because there is no direct call to objReports.Gene rate, and
objReports.Disp ose only runs when Sub objReports_Repo rtFinished gets called.

Any ideas?

Thanks again!
Giovanni Bassi

"Tom Shelton" <to*@mtogden.co m> wrote in message
news:ue******** *****@TK2MSFTNG P11.phx.gbl...
On 2003-10-15, Giovanni Bassi <gb****@coair.c om> wrote:
Hello Group,

I am running an operation in a different thread. There are resources that are released when the thread is done running. This is done at the end of the execution as it raises an event, and then the operation handling this event calls threaded object's dispose method.
The problem is: If an exception is thrown the event is never raised, the
operation never executes dispose and my resources get stuck on the memory until the app is finally closed and then, just then, the finalize method
will call the dispose method.
How can I know if an exception was thrown in a different thread? I need that to be able to call the dispose method myself and not wait until finalize
runs whenever it feels like.

Thanks in advance for all the replies,

Giovanni Bassi


I think you may want to check into Try-Catch-Finally... The finally
block is always executed - even if an exception is thrown. I'm not
exactly sure with out seeing some code of course, but I would guess this
is a code structure issue. Is there any way you can post a scaled down
snippet of code that illustrates what you are trying to accomplish?

--
Tom Shelton
MVP [Visual Basic]

Nov 20 '05 #3
On 2003-10-16, Giovanni Bassi <gb****@coair.c om> wrote:
Hey Tom,

Thanks for the Reply.
Here is what is some code:
This runs on a menu click handler:

Dim objReports As Reports
objReports = New ExcelPayrollCD( strFullFileName ,
g_objTables.Con nection, intSerial)
AddHandler objReports.Repo rtFinished, AddressOf
objReports_Repo rtFinished

Dim objNewThreadSta rt As New Threading.Threa dStart(AddressO f
objReports.Gene rate)
Dim objNewThread As New Threading.Threa d(objNewThreadS tart)
objNewThread.St art()

And there is this sub to handle the above code:

Private Sub objReports_Repo rtFinished(ByVa l sender As Excel.Reports)

Dim Result As Excel.ReportRes ults
Result = sender.ReportRe sult

Dim objNewThreadSta rt As New Threading.Threa dStart(AddressO f
CType(sender, IDisposable).Di spose)
Dim objNewThread As New Threading.Threa d(objNewThreadS tart)
objNewThread.St art()

Select Case Result
Case Excel.ReportRes ults.OK
MessageBox.Show ("Report created!" & vbNewLine &
sender.FullFile Name & " saved.", "Payroll CD", MessageBoxButto ns.OK,
MessageBoxIcon. Information, MessageBoxDefau ltButton.Button 1)
Case Excel.ReportRes ults.Cancelled
MessageBox.Show ("Report cancelled.")
Case Excel.ReportRes ults.Connection TimeOut
MessageBox.Show ("Connection Timed Out.")
Case Excel.ReportRes ults.DataNotRet rived
MessageBox.Show ("Data Not Retrived.")
Case Excel.ReportRes ults.ReportMode lNotFound
MessageBox.Show ("Report model not found.")
Case Excel.ReportRes ults.UnknownErr or
MessageBox.Show ("Unkown Error.")
Case Else

End Select

End Sub
I want to catch an error on objReports.Gene rate, which is run at
objNewThread.St art.
Normally, without MultiThreading, I'd simply do:

Try
objReports.Gene rate()
Catch
'do whatever
Finally
objReports.Disp ose
End Try

but I can't because there is no direct call to objReports.Gene rate, and
objReports.Disp ose only runs when Sub objReports_Repo rtFinished gets called.

Any ideas?

Thanks again!
Giovanni Bassi


Giovanni,

Looking over the code, assuming I understand what's happening :), I
would suggest you look into using an async delegate to call a method
that generates the report... I think you will save your self a lot of
trouble, and end up with the same results. Basically, what you would do
is create and call a method, called say GenerateReports , using async
delegate. The GenerateReports method would be as simple as:

Private Delegate Sub GenReportsDeleg ate()

' menu click...
Private Sub...
Dim async As New GenReportsDeleg ate(AddressOf Me.GenerateRepo rts)

' now call the method async like...
async.BeginInvo ke(AddressOf Me.GenerateRepo rtsComplete, Nothing)
End Sub

' Generate your reports in the background...
Private Sub GenerateReports ()
Dim objReports As Reports = _
New ExcelPayrollCD( strFullFileName , g_objTables.Con nection, intSerial)

AddHandler objReports.Repo rtFinished, AddressOf objReports_Repo rtFinished

Try
objReports.Gene rate()
Catch
' do whatever
Finally
objReports.Disp ose()
End Try
End Sub

' do this so you make sure EndInvoke is called
Private Sub GenerateReports Done(ByVal ar As IAsyncResult)
Dim async As GenReportsDeleg ate = _
DirectCast(ar.A syncState, GenReportsDeleg ate)

async.EndInvoke (ar)
End Sub

What will change, and I think for the better is that you will eliminate
all the explicit threading, since the system will manage the threads.
Not only that, in the end the code is simpler. I don't have the docs on
this machine to give you a reference in them, but you can find a pretty
good overview in the docs on MSDN...

http://msdn.microsoft.com/library/de...rogramming.asp

HTH
--
Tom Shelton
MVP [Visual Basic]
Nov 20 '05 #4

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

Similar topics

4
360
by: Jakob Bengtsson | last post by:
Hi I'm trying to show a form as a dialog (using the .ShowDialog() method). After showing the dialog, I want to dispose of the form I use this design (simplified to clarify the point) MyDialog dlg tr dlg = new MyDialog()
14
2792
by: Daniel Billingsley | last post by:
The example code for Memory shows it being used in a using() block. The documentation for using() says it can only be used on things that implement Disposable. Yet there is no Dispose() method for Memory. So, while using(Memory...) compiles fine, calling .Dispose() in a finally block wouldn't be possible. Those are supposed to be equivalents, aren't they? Who can untangle this one?
10
8203
by: Clint | last post by:
Hey all - I'm having a really confusing problem concerning a web service. Right now, I have an application that needs to call a web service that does nothing but return "true" (this will obviously change once the program's fully built to actually do something, but for testing, it works). The only code I added to the service is below:
0
2062
by: Joe | last post by:
Reposting here as there were no useful replies in the dotnet.framework NG... What is the correct pattern for handling exceptions in IDisposable.Dispose, especially in a class that manages multiple unmanaged resources? An example of such a class is System.ComponentModel.Container. I have always understood that the IDisposable contract was that Dispose guarantees to release unmanaged resources owned by the object - even if the Dispose...
1
22790
by: Sagaert Johan | last post by:
Hi Ii have a simple server thread in an app that listens for connections, for some unclear reason an exception is thrown every now and then : 'A blocking operation was interrupted by a call to WSACancelBlockingCall ' Any suggestion why this may happen ? The Exception is thrown by the svr.AcceptTcpClient() method See source below.
9
1526
by: Menny | last post by:
Hi, I'm looking for a way to determine if the 'Dispose()' function at the end of a 'using' block, was called due to an exception. Can anyone help?
54
5213
by: Zytan | last post by:
I have a log class that makes a synchronized TextWriter like so, in the constructor: StreamWriter sw = new StreamWriter(filename); tw = TextWriter.Synchronized(sw); In the destructor, ~MyLogClass(), I call: tw.WriteLine("some stuff"); tw.Close();
6
5126
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
3
2517
by: Rudi | last post by:
Hello, following problem: At program end or release an assembly a serial device should get a final exit sequence. How can I do this? With Dispose() it's no problem, but this assembly is used in a com interop dll and it must be guaranteed, that the final sequence is send to the serial device, when the calling application dont send Close() or Dispose().
0
8923
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
8763
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9428
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...
1
9203
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9151
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
6025
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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

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.