Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stream Object is null when I go to close it

Status
Not open for further replies.

ralphtrent

Programmer
Jun 2, 2003
958
US
Hello
I have the following situation. I have a windows service that multi threads a process. this process will then do its thing and then call a static class to write to a file. the file writing happens in an other object. In that file writer, I have the code to write call a function to create the stream, then return to the original code, write the data, close the file and destroy the object. For every write, it creates the stream. The problem is when I go to close the file, I get Object Reference not set to an Instance of an object Error .

Here is code flow:

Code:
Windows Service
 Threaded Code
  Transaction that will do the work
    Call Static Method with in current object
     Call Static Method within current class
      Create external object and call method
       Call Method in current class
        Call Method to create StreamWriter in current class
         Write To Stream in try\catch
          In finally close file and destroy object

I keep excepting in my finally block when I go to close the file. I think the threads are stepping on themselves and causing this but I have no clue.

I can provide code but it may be too much.

Here is my createStream Code
Code:
private void createStream(string messageLogPath)
{
	StreamWriter gswMessageLog;
	if (String.Compare(messageLogPath, String.Empty) == 0)
	{
		throw new FileNotFoundException("Can not save to output log. No output log file was specified.");
	}
	try
	{
		gswMessageLog = new StreamWriter(messageLogPath, true);
		gtwMessageLog = StreamWriter.Synchronized(gswMessageLog);
	}
	catch (System.IO.IOException)
	{
		try { gswMessageLog = new StreamWriter(messageLogPath, true); }
        	catch { throw; }
	}
}

but here is my code that is excepting:
Code:
private void saveMessage(string messageLogPath, string message)
{
	try
	{
		createStream(messageLogPath);
		foreach (string lstrLine in message.Split('\n'))
		{
			if (String.Compare(lstrLine, String.Empty) == 1)
			{
				gtwMessageLog.Write(dateForStartOfLine());
				gtwMessageLog.Write(Convert.ToString('\t'));
				gtwMessageLog.Write(string.Format("{0}:{1}", System.Diagnostics.Process.GetCurrentProcess().Id, System.Threading.Thread.CurrentThread.ManagedThreadId));
				gtwMessageLog.Write(Convert.ToString('\t'));
				gtwMessageLog.WriteLine(lstrLine);
                	}
        	}
        }
        catch { throw; }
	finally
	{
		gtwMessageLog.Close(); [green]// THIS IS WHERE I FAIL[/green]
        	gtwMessageLog = null;
	}
}

Any help is appreciated.

Thanks,
RalphTrent
 
I can see a problem with your code that MAY be hiding the underlying error:

In your finally block you should check that gtwMessageLog is not null before calling the Close() method.

Code:
finally
{
    if (gtwMessageLog != null)
        gtwMessageLog.Close();

    gtwMessageLog = null;  // Not sure if this is needed but will not do any harm.
}

I say this because if your code errors when trying to instantiate gtwMessageLog, another exception will be thrown in the finally block because the object is null but you are still trying to call the Close() method.

Fix that and see if you get a more meaningful error message.
 
I would put a break in my try block and step thru the code to see what is going on Also look at your gtwMessageLog and messagepath. Does your program see them inside the try?

Is your stream still open when you leave the try block?
 
PG if I do that then I think I would be breaking logic no? Meaning if I create and open a file stream, I should be forced to close it.

PR, The code works fine, but it blows up randomly. Meaning, the service runs every 15 minutes, it may work fine for the first cycle, but then blow up the second time around.

Very weird.
 
The code works fine, but it blows up randomly. Meaning, the service runs every 15 minutes, it may work fine for the first cycle, but then blow up the second time around.
if it blows up the 2nd time around then it's no longer random. it sounds like you are not properly releasing the streams after you are finished using them, or they are not released if an exception is thrown.

I don't see were you call Dispose() on the Stream. this is crucial to managing resources.

It also appears that you are closing the stream in a different place then where you are creating the stream. the problem with this is misplaced responsibility. the function saveMessage should only write to the stream it shouldn't close/dispose the stream since it did not create the stream.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
PG if I do that then I think I would be breaking logic no? Meaning if I create and open a file stream, I should be forced to close it."

Absolutely but I'm saying if an error occurs when you are trying to create the stream (in other words it doesn't get created) then another error will be thrown in the finally block when you are trying to close it.
 
By the way in this situation you would get an "Object reference not set to an instance of an object" exception. That is why I think it may be a possibility here...
 
jmeckly
I was using the second time around as an example, it may be the third, forth or fifth or whatever. What I was trying to say is that the first time round it may work, so I was just replying to the "Does your program see them inside the try?" comment. The object is seen by the code, it just randomly gets this issue. I will try the dispose method, but I will also move my "Create stream" code into the actual function.

Thanks.
 
I have been running with out error since 11:32 am est. I update saveMessage to create the stream, write the file, and then dispose and nullify the object. So far, so good. I hope this will continue.

Thanks everyone.

RalphTrent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top