473,657 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Threadin g.Monitor.Enter (this);
FileStream fs = new FileStream(file Name, FileMode.OpenOr Create,
FileAccess.Read Write);
StreamWriter sw = new StreamWriter(fs );
sw.BaseStream.S eek(0, SeekOrigin.End) ;
sw.WriteLine("e tcetc");
sw.Flush();
sw.Close();

System.Threadin g.Monitor.Pulse (this);
System.Threadin g.Monitor.Exit( this);
}

Any help is appreciated, I am new to threading.
Nov 16 '05 #1
3 6234
Chris Fink <Ch*******@disc ussions.microso ft.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.Threadin g.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.co m>
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*******@disc ussions.microso ft.com> wrote in message
news:DB******** *************** ***********@mic rosoft.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.Threadin g.Monitor.Enter (this);
FileStream fs = new FileStream(file Name, FileMode.OpenOr Create,
FileAccess.Read Write);
StreamWriter sw = new StreamWriter(fs );
sw.BaseStream.S eek(0, SeekOrigin.End) ;
sw.WriteLine("e tcetc");
sw.Flush();
sw.Close();

System.Threadin g.Monitor.Pulse (this);
System.Threadin g.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
3722
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
8493
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
2133
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 when I got two threads going at the same time. What I have is two text boxes (textBox1 and textBox2) and four buttons(cmdStartThread1, cmdStartThread2, cmdStopThread1, cmdStopThread2)
9
2455
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 should build a database-connection and send a few sqls
2
2307
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 I just wanted to ask if I am missing anything based on the following scenario. My test app pulls data from a large external data source which has a table-like structure (but not rdbms - more
5
2360
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 table "appointment" are as follows: noapp* (int4):ID Number of appointment (PK)
55
3299
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 call operations on Controls from a delegate, otherwise it does not work. However each time I've done an operation, I must update the progressbar and progresslabel, but this cannot be done in the delegate as it does not work.
5
2483
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 multithreading online using C# .
2
2253
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 divided the complete drawing into 3 parts..1st will be done by main thread and other two are done in these procedures - <1LongTimeTask <2LongTimeTask2 I have invoked the threads using below method. **************
7
16301
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 Exceptional C++, for example). Platform-specific (e.g.: Win32, POSIX) is OK, as long as it's good :) Thank you, Ray
0
8395
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
8310
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
8826
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...
0
8732
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...
1
8503
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,...
1
6166
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
4155
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
4306
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1615
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.