473,786 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(strin g 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(file Name,
FileMode.Open, FileAccess.Read , FileShare.Read) ;
rRead = new StreamReader(fS tream,System.Te xt.Encoding.ASC II);
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 8305
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******** ******@TK2MSFTN GP10.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(strin g 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(file Name,
FileMode.Open, FileAccess.Read , FileShare.Read) ;
rRead = new StreamReader(fS tream,System.Te xt.Encoding.ASC II);
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
NullReferenceEx ception.

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.co m

"William Stacey" <st***********@ mvps.org> wrote in message
news:Oz******** ******@TK2MSFTN GP11.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******** ******@TK2MSFTN GP10.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(strin g 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(file Name,
FileMode.Open, FileAccess.Read , FileShare.Read) ;
rRead = new StreamReader(fS tream,System.Te xt.Encoding.ASC II);
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.c om> wrote in
message news:u1******** ******@TK2MSFTN GP11.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
NullReferenceEx ception.

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.co m

"William Stacey" <st***********@ mvps.org> wrote in message
news:Oz******** ******@TK2MSFTN GP11.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******** ******@TK2MSFTN GP10.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(strin g 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(file Name,
FileMode.Open, FileAccess.Read , FileShare.Read) ;
rRead = new StreamReader(fS tream,System.Te xt.Encoding.ASC II);
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******** ******@TK2MSFTN GP09.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
2256
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 multithreaded operations. Any instance members are not guaranteed to be thread safe." I have 2 questions: 1. I thought dynamic variables are thread-safe since threads have their own
4
5787
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 to do : Class.method(InstanceOfClass); The method would then access a private function from Class by doing something like
12
2048
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 for all Balances to be 0. When using an Integer things work fine. LONGS do not. We are using the Interlocked methods. I believe the Interlocked.Add method is not thread safe when using longs on 32bit systems. We are aware of...
15
2786
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 Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.' So, does this mean All the static/shared methods written in .NET compatible programming language, such as C#, VB.NET, are guaranteed to be...
1
3573
by: kiluyar | last post by:
I have such a function: class T { public: T(){...//some operations} }; T& GetInst()
0
9492
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
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9960
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
8988
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...
0
6744
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
5397
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
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4064
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
3
2894
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.