473,387 Members | 1,585 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Multithreading and syncronization

I have written a dll that performs file IO that will be called frequently. I
have been running into problems where file locking is occuring when a thread
cannot access the file since it is being used. How do I lock this IO
operation down while it is being used and tell the other threads to wait
until the IO is complete - like waiting in a checkout line? I have looked
into numerous examples, but just cannot find anything that relates to file IO
that works.
lock(this)
{
System.Threading.Monitor.Enter(this);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("etcetc");
sw.Flush();
sw.Close();

System.Threading.Monitor.Pulse(this);
System.Threading.Monitor.Exit(this);
}

Any help is appreciated, I am new to threading.
Nov 16 '05 #1
3 6217
Chris Fink <Ch*******@discussions.microsoft.com> wrote:
I have written a dll that performs file IO that will be called frequently. I
have been running into problems where file locking is occuring when a thread
cannot access the file since it is being used. How do I lock this IO
operation down while it is being used and tell the other threads to wait
until the IO is complete - like waiting in a checkout line? I have looked
into numerous examples, but just cannot find anything that relates to file IO
that works.
Well, it's not *really* an IO-specific problem.
lock(this)
{
System.Threading.Monitor.Enter(this);


There's no need to use Monitor.Enter if you've already got "lock" -
they're equivalent. (I wouldn't recommend locking on "this" though.)

I suggest you use a semaphore for each resource - there's no semaphore
in .NET pre-2.0, but it's fairly easy to write one. (There may well be
one available on the web.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
You're on the right track, but there are a couple of changes you need to
make and a few issues to be aware of.

1) You should remove all the calls to the Monitor object. The "lock"
statement is equivalent to calling Monitor.Enter() when the block starts and
Monitor.Exit() when the block ends. The Monitor.Pulse() call is only useful
when you also use Monitor.Wait(), but I don't think you need either for what
you're doing.

2) Because you're using "this" as your synchronization object, your code
will only ensure concurrent access to the file for threads accessing the
same instance of whatever class contains the code below. If your class will
have multiple instances which all need to be synchronized, then use "lock
(this.GetType())". This will lock on the class's Type object, which is
shared for all instances, thus synchronizing all instances of the class.

3) Even if you make the change in item #2, this makes the assumption that
the only code that will attempt to access this file is within this one
class. If you have other code in other classes that may access the same
file, then you need to ensure synchronization regardless of which class
accesses the file. To do this, I'd recommend breaking the file access code
into a new class so that all accesses go through there. Then locking on the
object's type should work.

4) All of that said, none of this protects you against locks held by other
processes. I don't know of any way to have the code block until a filesystem
lock is released. To simulate this, you can try to open the file, catch the
IOException, perhaps call Thread.Sleep for a second or so and try again.

Hope that helps -
Ken
"Chris Fink" <Ch*******@discussions.microsoft.com> wrote in message
news:DB**********************************@microsof t.com...
I have written a dll that performs file IO that will be called frequently. I have been running into problems where file locking is occuring when a thread cannot access the file since it is being used. How do I lock this IO
operation down while it is being used and tell the other threads to wait
until the IO is complete - like waiting in a checkout line? I have looked
into numerous examples, but just cannot find anything that relates to file IO that works.
lock(this)
{
System.Threading.Monitor.Enter(this);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("etcetc");
sw.Flush();
sw.Close();

System.Threading.Monitor.Pulse(this);
System.Threading.Monitor.Exit(this);
}

Any help is appreciated, I am new to threading.

Nov 16 '05 #3
Chris Fink wrote:
I have written a dll that performs file IO that will be called frequently. I
have been running into problems where file locking is occuring when a thread
cannot access the file since it is being used. How do I lock this IO
operation down while it is being used and tell the other threads to wait
until the IO is complete - like waiting in a checkout line? I have looked
into numerous examples, but just cannot find anything that relates to file IO
that works.


Hi, I'm complete newbie in C# lang. I know this problem fom another platform. My solution was this:

implement sync object which is type of a queue

- your thread will add itself to this queue and then goes to sleep
- will be wakened by queue when is ready to write
- after writing, remove self from queue (call a method queue.remove(me))- this operation will tell the queue, that another process should be wakened ...
Nov 16 '05 #4

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

Similar topics

47
by: mihai | last post by:
What does the standard say about those two? Is any assurance that the use of STL is thread safe? Have a nice day, Mihai.
16
by: Robert Zurer | last post by:
Can anyone suggest the best book or part of a book on this subject. I'm looking for an in-depth treatment with examples in C# TIA Robert Zurer robert@zurer.com
5
by: sarge | last post by:
I would like to know how to perform simple multithreading. I had created a simple form to test out if I was multithreading properly, but got buggy results. Sometime the whole thig would lock up...
9
by: tommy | last post by:
hi, i have found a example for multithreading and asp.net http://www.fawcette.com/vsm/2002_11/magazine/features/chester/ i want to speed up my website ... if my website is starting, they...
2
by: Rich | last post by:
Hello, I have set up a multithreading routine in a Test VB.net proj, and it appears to be working OK in debug mode and I am not using synchronization. Multithreading is a new thing for me, and...
5
by: Prabu Subroto | last post by:
Dear my friends... I am using SuSE Linux 9.1 and postgres. I am a beginner in postgres, usually I use MySQL. I have 3 tables : appointment, appointment0 and appointment1. the fields of...
55
by: Sam | last post by:
Hi, I have a serious issue using multithreading. A sample application showing my issue can be downloaded here: http://graphicsxp.free.fr/WindowsApplication11.zip The problem is that I need to...
5
by: sandy82 | last post by:
Whats actuallly multithreading is ... and how threading and multithreading differ . Can any1 guide how multithreading is used on the Web .. i mean a practical scenario in which u use...
2
by: Pradnya Patil | last post by:
hi , I am trying to draw ' html div-tag ' on the screen which will resemble a rectangle through vb.net code. I want it to be drawn faster...so I introduced multithreading using Threadpool. I...
7
by: Ray | last post by:
Hello, Greetings! I'm looking for a solid C++ multithreading book. Can you recommend one? I don't think I've seen a multithreading C++ book that everybody thinks is good (like Effective C++ or...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...

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.