473,840 Members | 1,558 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 8312
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
2261
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
5796
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
2053
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
2790
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
3575
by: kiluyar | last post by:
I have such a function: class T { public: T(){...//some operations} }; T& GetInst()
0
9861
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
10924
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
10665
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
10301
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
7839
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
7023
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
5685
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
5874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
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

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.