473,721 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In case FileStream fails, the GC throws an exception in another thread that cannot be caught


Hi!
In the example below, once the media is full, the FileSteam.Write Byte throws
an exception and the code
is designed to handle it. However, when the GC is invoked, it calls the
Finalize of FileSteam, who is trying
to flush and close the stream, but the disk is full, so the flush fails and
another exception is thrown from another
(GC) thread. An ugly solution would be to use GC.SuppressFina lize(fs).
Is there a better solution or good practice? (closing withot flushing
perhaps)?

many thanks,
M. Rapp

--------------------------------

Example:

static void Main(string[] args)
{
try
{
FileStream fs =
new FileStream(args[0], FileMode.Create );
Console.WriteLi ne("starting to write...");
while (true)
fs.WriteByte(0x ff);
}
catch (Exception e)
{
Console.WriteLi ne("Exception: {0}",
e.Message);
}
Console.WriteLi ne("press any key to continue");
Console.Read();
}
Nov 15 '05 #1
3 6306
Have you tried wrapping the use of your FileStreamer in a "using" block?
Something like:

using(FileStrea m fs =
new FileStream(args[0], FileMode.Create )) {
Console.WriteLi ne("starting to write...");
while (true)
fs.WriteByte(0x ff);
}

You can always wrap the using block inside your try/catch block, but using
the implicit Dispose pattern you should be able to force the finalization to
occur in your thread (if I am not wrong).

using(
"Muki Rapp" <ra**@notalvisi on.com> wrote in message
news:uI******** ******@TK2MSFTN GP11.phx.gbl...

Hi!
In the example below, once the media is full, the FileSteam.Write Byte throws an exception and the code
is designed to handle it. However, when the GC is invoked, it calls the
Finalize of FileSteam, who is trying
to flush and close the stream, but the disk is full, so the flush fails and another exception is thrown from another
(GC) thread. An ugly solution would be to use GC.SuppressFina lize(fs).
Is there a better solution or good practice? (closing withot flushing
perhaps)?

many thanks,
M. Rapp

--------------------------------

Example:

static void Main(string[] args)
{
try
{
FileStream fs =
new FileStream(args[0], FileMode.Create );
Console.WriteLi ne("starting to write...");
while (true)
fs.WriteByte(0x ff);
}
catch (Exception e)
{
Console.WriteLi ne("Exception: {0}",
e.Message);
}
Console.WriteLi ne("press any key to continue");
Console.Read();
}

Nov 15 '05 #2
Hi!
I am afraid this is not the solution to the problem.
'using' will force the dispose method to be called and
exception to be thrown in the same thread, but still
at the end of the process the GC will also try to dispose
the filestream and an exception will be thrown in a DIFFERENT thread (run
example below for demonstration,
when filename path is a small floppy disk)

Any other ideas?

try
{
using(FileStrea m fs =
new FileStream(args[0], FileMode.Create ))
{

while (true)
fs.WriteByte(0x ff);

}
}
catch (Exception e)
{
Console.WriteLi ne("Exception: " + e.Message);
}

"Stefano "WildHeart" Lanzavecchia" <st********@apl .it> wrote in message
news:u4******** *****@tk2msftng p13.phx.gbl...
Have you tried wrapping the use of your FileStreamer in a "using" block?
Something like:

using(FileStrea m fs =
new FileStream(args[0], FileMode.Create )) {
Console.WriteLi ne("starting to write...");
while (true)
fs.WriteByte(0x ff);
}

You can always wrap the using block inside your try/catch block, but using
the implicit Dispose pattern you should be able to force the finalization to occur in your thread (if I am not wrong).

using(
"Muki Rapp" <ra**@notalvisi on.com> wrote in message
news:uI******** ******@TK2MSFTN GP11.phx.gbl...

Hi!
In the example below, once the media is full, the FileSteam.Write Byte

throws
an exception and the code
is designed to handle it. However, when the GC is invoked, it calls the
Finalize of FileSteam, who is trying
to flush and close the stream, but the disk is full, so the flush fails

and
another exception is thrown from another
(GC) thread. An ugly solution would be to use GC.SuppressFina lize(fs).
Is there a better solution or good practice? (closing withot flushing
perhaps)?

many thanks,
M. Rapp

--------------------------------

Example:

static void Main(string[] args)
{
try
{
FileStream fs =
new FileStream(args[0], FileMode.Create );
Console.WriteLi ne("starting to write...");
while (true)
fs.WriteByte(0x ff);
}
catch (Exception e)
{
Console.WriteLi ne("Exception: {0}",
e.Message);
}
Console.WriteLi ne("press any key to continue");
Console.Read();
}


Nov 15 '05 #3
> > > An ugly solution would be to use GC.SuppressFina lize(fs).
Is there a better solution or good practice? (closing withot flushing perhaps)?


I think you will have to use GC.SuppressFina lize(fs) after trying a
call to Dispose() or close() or using statement.
The FileStream's dispose (and IMO most "good" dispose methods) call
GC.SuppressFina lize at the end of the method call. However, because
of the exception, it is not getting called. So I wouldn't feel too
bad about manually supressing finalization.

I can't think of any other way to prevent an exception from being
raised on the Finalizer thread or catching that exception once thrown.

// a sample dispose function
void Dispose()
{
Dispose(true); // exception firing within this event...
GC.SuppressFina lize(this);
}

Although I do wonder if the file will continue to be locked since
Dispose was never called successfully. In the below program, it does
look like the file will be locked. Argh!

public static void Main ()
{
FileStream fs = new FileStream(@"A: \new.txt",
FileMode.Create );
bool diskfull = false;
try
{
while (true)
fs.WriteByte(0x ff);
}
catch (IOException e)
{
Console.WriteLi ne("Exception: " + e.Message);
diskfull = true; // technically should only be set for
IOException when disk really is full.
}
finally
{
if (diskfull)
{
GC.SuppressFina lize(fs);
}
else
{
fs.Close();
}
}

// let's check to see if the file is locked.
try
{
using (FileStream fs1 = new FileStream(@"A: \new.txt",
FileMode.Open))
{
fs.ReadByte();
}
}
catch (Exception ex)
{
Console.WriteLi ne ("Exception: " + ex.Message);
}

Console.ReadLin e();
}

Nov 15 '05 #4

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

Similar topics

0
4545
by: John | last post by:
I've got multiple threads and processes that write to same file. Before writing all threads / processes first lock part of file and then write to file. If one thread / process locks file, another threads / processes can not lock this file again. And I want that all threads / processes wait until first thread frees lock by calling FileStream.Unlock. But I do not know what code should I use that all threads / processes wait until first...
2
2194
by: pegazik | last post by:
Hello. I have problem and I ask you for help. Probably there is some quite easy solution, but I can't see it. I'm trying to perform some action that have to be timeout safe. So here is the structure of my program: \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ def TimeoutHandler():
8
1957
by: Robert Gravereaux | last post by:
I've noticed that the first exception thrown/caught by an app running in debug is very slow - it takes perhaps 7 or 8 seconds on my P4 machine. I've noticed this on several different machines running the development environment. To replicate, create a new c# windows app, add a button, and hook it to the following code: private void btnException_Click(object sender, System.EventArgs e) { try
5
27391
by: David | last post by:
I am having a bit of a problem with catching an exception within a thread. Here is the scenario: I have a Windows Form. I create a new thread. This new thread calls a method in another DLL that catches an expected exception. The method in the DLL throws the exception back out. When in debug mode, the process just exits.
4
5511
by: Anders Borum | last post by:
Hello! I am working on improving my threading skills and came across a question. When working with the ReaderWriterLock class, I am getting an unhandled exception if I acquire a WriterLock with a timeout less than the time required to process the code section it protects. The code listed below is just a small application I wrote to check the behavious of the different threading / synchronization techniques. Basically the application...
4
2038
by: Rob Richardson | last post by:
Greetings! I am working on an application that targets a Pocket PC running Windows CE and SQL Server CE. Almost all functions in the application use a Try block with a Catch block that looks like this: Try TryToDoIt() Catch e as Exception LogTheError(e)
0
1786
by: upendra.desai | last post by:
Hi, I have written an application in Microsoft Visual C++ (Visual Studio 6.0) that uses MSXML 4.0 SP2. When I try to load an XML from a file, it throws an E_ACCESSDENIED (HRESULT = 0x80070005) exceptioon. I am not sure why this is happenning. The sample code is: IXMLDOMDocument2Ptr spXMLDocument; spXMLDocument.CreateInstance(CLSID_DOMDocument40);
110
10605
by: alf | last post by:
Hi, is it possible that due to OS crash or mysql itself crash or some e.g. SCSI failure to lose all the data stored in the table (let's say million of 1KB rows). In other words what is the worst case scenario for MyISAM backend? Also is it possible to not to lose data but get them corrupted?
6
1941
by: Emre DÝNÇER | last post by:
does c# provide an alternative to the throws keyword in javA?so that my client developer will strictly implement the exceptions that my methods may throw? thanks in advance
0
9367
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
9131
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
9064
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...
1
6669
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
5981
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
4484
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
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
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.