473,748 Members | 6,037 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 1961
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
2793
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
8205
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
2064
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
22795
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
1527
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
5221
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
5128
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
2518
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
8991
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
8830
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
9544
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
8243
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
6796
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...
0
6074
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
4606
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...
2
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.