472,374 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,374 software developers and data experts.

Is this public static method for reading files thread safe

GG
Is this public static method thread safe.

//Receives a file name as a parameter
//and returns the contents of that file as a string
public static string FileToStr(string fileName)
{
FileStream fStream=null;
lock(fStream) //just in case we use it for multithreading to be thread
safe
{
StreamReader rRead = null;
string fileData=null;
try
{
fStream= new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
rRead = new StreamReader(fStream,System.Text.Encoding.ASCII);
fileData=rRead.ReadToEnd();
}
catch(Exception eFile)
{
throw eFile;
}
finally
{
rRead.Close();
fStream.Close();
}
return fileData;
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #1
6 8200
Not really. Your locking a local instance of a filestream object that will
be a different object on each call. Lock a static reference type field
instead. (ie. public static lockobj = new object() )
--wjs mvp

"GG" <gg@hotmail.com> wrote in message
news:O2**************@TK2MSFTNGP10.phx.gbl...
Is this public static method thread safe.

//Receives a file name as a parameter
//and returns the contents of that file as a string
public static string FileToStr(string fileName)
{
FileStream fStream=null;
lock(fStream) //just in case we use it for multithreading to be thread
safe
{
StreamReader rRead = null;
string fileData=null;
try
{
fStream= new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
rRead = new StreamReader(fStream,System.Text.Encoding.ASCII);
fileData=rRead.ReadToEnd();
}
catch(Exception eFile)
{
throw eFile;
}
finally
{
rRead.Close();
fStream.Close();
}
return fileData;
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #2
Actually, the method is thread safe, as it is using only local
variables.

However, there is an error in the code. If you try and call the lock
statement on a reference that is null, you should get a
NullReferenceException.

Because the method is using only local variables, the lock can be
removed, and it should work just fine.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"William Stacey" <st***********@mvps.org> wrote in message
news:Oz**************@TK2MSFTNGP11.phx.gbl...
Not really. Your locking a local instance of a filestream object that will be a different object on each call. Lock a static reference type field
instead. (ie. public static lockobj = new object() )
--wjs mvp

"GG" <gg@hotmail.com> wrote in message
news:O2**************@TK2MSFTNGP10.phx.gbl...
Is this public static method thread safe.

//Receives a file name as a parameter
//and returns the contents of that file as a string
public static string FileToStr(string fileName)
{
FileStream fStream=null;
lock(fStream) //just in case we use it for multithreading to be thread
safe
{
StreamReader rRead = null;
string fileData=null;
try
{
fStream= new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
rRead = new StreamReader(fStream,System.Text.Encoding.ASCII);
fileData=rRead.ReadToEnd();
}
catch(Exception eFile)
{
throw eFile;
}
finally
{
rRead.Close();
fStream.Close();
}
return fileData;
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


Nov 15 '05 #3
GG
>Not really. Your locking a local instance of a filestream >object that
will be a different object on each call.
So I do not need any lock if the same app through multiple threads is
calling the same method?
Lock a static reference type field
instead. (ie. public static lockobj = new object() )

Can you please explain. I do not follow.

Thanks

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #4
I assume his intention for the lock, was have exclusive lock to the file
(which he could do other ways). If that was not the case, he would not need
to use a lock at all and use local vars as you said, which would be thread
safe.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:u1**************@TK2MSFTNGP11.phx.gbl...
Actually, the method is thread safe, as it is using only local
variables.

However, there is an error in the code. If you try and call the lock
statement on a reference that is null, you should get a
NullReferenceException.

Because the method is using only local variables, the lock can be
removed, and it should work just fine.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"William Stacey" <st***********@mvps.org> wrote in message
news:Oz**************@TK2MSFTNGP11.phx.gbl...
Not really. Your locking a local instance of a filestream object that

will
be a different object on each call. Lock a static reference type field
instead. (ie. public static lockobj = new object() )
--wjs mvp

"GG" <gg@hotmail.com> wrote in message
news:O2**************@TK2MSFTNGP10.phx.gbl...
Is this public static method thread safe.

//Receives a file name as a parameter
//and returns the contents of that file as a string
public static string FileToStr(string fileName)
{
FileStream fStream=null;
lock(fStream) //just in case we use it for multithreading to be thread safe
{
StreamReader rRead = null;
string fileData=null;
try
{
fStream= new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
rRead = new StreamReader(fStream,System.Text.Encoding.ASCII);
fileData=rRead.ReadToEnd();
}
catch(Exception eFile)
{
throw eFile;
}
finally
{
rRead.Close();
fStream.Close();
}
return fileData;
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!



Nov 15 '05 #5
Not sure what your trying to lock here. Is your intention to allow only one
thread to access the method at any one time? If so, as the method is
static, you can't lock on an instance field, like "this" or other. You can
lock on the class itself (i.e. lock(MyClass) IIRC) or create a static field
and lock on it.
Doing this from memory here:
public class MyClass
{
public static readonly object mySyncLock = new object(); //Set once.
private int someInt;
//...
public MyClass()
{
}
public static bool MyMethod(int myInt)
{
//Do stuff not needing the lock if needed.
lock(mySyncLock)
{
//Do stuff that requires exclusive access to some resource.
}// exits lock
//Do other stuff not needing the lock if needed.
}
}
HTH
--wjs
"GG" <gg@hotmail.com> wrote in message
news:OM**************@TK2MSFTNGP09.phx.gbl...
Not really. Your locking a local instance of a filestream >object that

will be a different object on each call.
So I do not need any lock if the same app through multiple threads is
calling the same method?
Lock a static reference type field
instead. (ie. public static lockobj = new object() )

Can you please explain. I do not follow.

Thanks

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #6
GG
Thanks everybody for clearing it up for me.

My intention is not to have exclusive lock to the file
but instead to call the same static method from the same app with
multiple threads and be thread safe.

As you recommented I will remove the lock and will do what I need.

Thanks again.


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #7

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

Similar topics

11
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for...
4
by: rognon | last post by:
Hi there, I'm trying to do something, but I don't know if it's possible. Basically, I want to have a public static class method that could access a private object's method. I would like to be able...
12
by: David | last post by:
Below are three classes for a console application. If put into three separate files, the sub main() will launch multiple threads adding and removing the same value. At the end we expect the value...
15
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual...
1
by: kiluyar | last post by:
I have such a function: class T { public: T(){...//some operations} }; T& GetInst()
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...
0
by: F22F35 | last post by:
I am a newbie to Access (most programming for that matter). I need help in creating an Access database that keeps the history of each user in a database. For example, a user might have lesson 1 sent...

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.