Concurrent access to private data

Hi,

maybe it's a simple problem for most of you, but I can't find an easy way to 
quite simple problem, let me describe:

Let's have this code:

public ClassToChange()
{
	... //some other methods

	internal List<AnyDataClass> LockAndGetData()
	{
		Monitor.Enter(cs);
		return data;
	}

	internal Unlock()
	{
		Monitor.Exit(cs);
	}

	private object cs = new object();
	private List<AnyDataClass> data = new List<AnyDataClass>();
}

public class Editor
{
	public Editor(ClassToChange editedObject)
	{
		this.editedObject = editedObject;
	}

	public void MyFunctionToChangeData()
	{
		List<AnyDataClass> data = editedObject.LockAndGetData();
		
		... // change data

		editedObject.Unlock();
	}

	private ClassToChange editedObject;
}


class Program
{
	static void Main()
	{
		Editor ed = new Editor(new ClassToChange());
		ed.MyFunctionToChangeData();
	}
}

So my aim is to let Editor change the data of ClassToChange in a thread-safe 
way. But as you can see to call all the List data = 
editedObject.LockAndGetData(), then not to forget the editedObject.Unlock() 
is very boring to write (and not so safe). Do you have any easy solution for 
this?

Only solution I have, there might be the CS as attribute of ClassToChange 
and use lock {} in Editor, but I would need an attribute to every data object 
of ClassToChange, who would check if the cs is locked to make it safe. So 
that's also not a good way.

Any ideas?
0
Utf
4/27/2010 9:25:01 AM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

13 Replies
1252 Views

Similar Articles

[PageSpeed] 39

Michal wrote:
> [...]
> So my aim is to let Editor change the data of ClassToChange in a thread-safe 
> way. But as you can see to call all the List data = 
> editedObject.LockAndGetData(), then not to forget the editedObject.Unlock() 
> is very boring to write (and not so safe). Do you have any easy solution for 
> this?
> 
> Only solution I have, there might be the CS as attribute of ClassToChange 
> and use lock {} in Editor, but I would need an attribute to every data object 
> of ClassToChange, who would check if the cs is locked to make it safe. So 
> that's also not a good way.
> 
> Any ideas?

If the synchronization needs to happen at the level of operations within 
the Editor class, then your synchronization object should also be in the 
Editor class.

Of course, this means that the Editor class has to be the de facto owner 
of your ClassToChange instance, and no other code should be modifying 
the ClassToChange instance while the Editor class is manipulating it. 
But that's just good program design anyway.  It should not be a problem 
to require that.

In some cases, it may be feasible to simply make the ClassToChange class 
the thread-safe one.  In that case, rather than having the Editor class 
try to lock and unlock, just do the synchronization in the ClassToChange 
class for each operation that might modify the class's contents.  This 
would lead to more locking and unlocking, but coherency of the data 
would still be preserved.

Finally, if you decide that neither of the above can possibly work (and 
I would recommend strongly that you not come to that conclusion…in 
particular, in your example it really looks like the synchronization 
should be handled entirely by the Editor class, with the ClassToChange 
class being left not thread safe), you could implement a "do work" 
interface in your ClassToChange class, so that the Editor class simply 
passes a delegate that is invoked while the lock is held.  For example:

class ClassToChange
{
   void DoSynchronizedWork(Action action)
   {
     lock (cs)
     {
       action();
     }
   }

   private readonly object cs = new object();
}

class Editor
{
   public void MyFunctionToChangeData()
   {
     editedObject.DoSynchronizedWork(MyFunctionToChangeDataImpl);
   }

   private void MyFunctionToChangeDataImpl()
   {
     // change data
   }

   private ClassToChange editedObject;
}

Hope that helps.

Pete
0
Peter
4/27/2010 10:00:05 AM
Hello,

> So my aim is to let Editor change the data of ClassToChange in a 
> thread-safe
> way. But as you can see to call all the List data =
> editedObject.LockAndGetData(), then not to forget the 
> editedObject.Unlock()
> is very boring to write (and not so safe). Do you have any easy solution 
> for
> this?

Try the SyncLock statement that is intended to simplify Enter/Exit calls. 
The doc is at :

http://msdn.microsoft.com/en-us/library/3a86s51t(VS.80).aspx

--
Patrice
 


0
Patrice
4/27/2010 10:02:41 AM
Patrice wrote:
> Try the SyncLock statement that is intended to simplify Enter/Exit calls. 
> The doc is at :
> 
> http://msdn.microsoft.com/en-us/library/3a86s51t(VS.80).aspx

This is the C# newsgroup.  The equivalent is the "lock" statement. 
Neither VB.NET's "SyncLock" nor C#'s "lock" offer the semantics that the 
OP is asking for (i.e. retaining the lock across method calls).

Granted, as I suggested in my reply to the OP, the semantics being asked 
for should be avoided.  :)  Nevertheless, I don't think that suggesting 
"lock" (or "SyncLock", were this a VB.NET newsgroup) would in and of 
itself suffice to answer the question.

Pete
0
Peter
4/27/2010 10:14:39 AM
> This is the C# newsgroup.  The equivalent is the "lock" statement. Neither 
> VB.NET's "SyncLock" nor C#'s "lock" offer the semantics that the OP is 
> asking for (i.e. retaining the lock across method calls).

Good point. Sometimes I just mix groups.

IMO retaining the lock was not the OP intent and was more caused by the 
implementation attempt...

--
Patrice 


0
Patrice
4/27/2010 11:00:11 AM
Thanks Peter, that's quite interesting solution. But also quite lot of 
writing. I know it's best to keep all the code for changing data inside 
class. But like this the class will get huge. E.g. imagine class for Bezier 
curve - to make all the operations like rotate, move, resize, ... inside it's 
awful. I ended up with 3500 lines in one cpp file in one of my projects, 
that's not acceptable.

My idea is to provide some kind of "editors" for class, which would change 
it. Something similar to MVC pattern maybe(?). Like this the operation is in 
once class and it does only what it has to. The only problem is this 
synchronization.
0
Utf
4/27/2010 4:46:04 PM
Michal wrote:
> Thanks Peter, that's quite interesting solution. But also quite lot of 
> writing.

It's no more typing ("writing") than your proposed solution of having 
separate lock/unlock methods that have to be called while you operate on 
an instance.  But I agree, it's not the best choice.  I simply offer it 
only in case you won't or can't make the best choice.

> I know it's best to keep all the code for changing data inside 
> class. But like this the class will get huge. E.g. imagine class for Bezier 
> curve - to make all the operations like rotate, move, resize, ... inside it's 
> awful. I ended up with 3500 lines in one cpp file in one of my projects, 
> that's not acceptable.

In general, classes like that are not thread-safe.  Why do you think 
yours should be?

> My idea is to provide some kind of "editors" for class, which would change 
> it. Something similar to MVC pattern maybe(?). Like this the operation is in 
> once class and it does only what it has to. The only problem is this 
> synchronization.

As I mentioned before, typically you make access to a type thread-safe, 
rather than making the type itself thread-safe.  Every now and then, you 
wind up with a type that is used _only_ in a threaded context, and where 
every member or almost every member may be accessed by two or more 
threads simultaneously.  In those cases, making the type thread-safe 
makes sense.  But those are rare exceptions.

This is true for at least a couple of reasons: reusable types most 
frequently do not need to be thread-safe, so making them thread-safe 
causes client code using the class to suffer unneeded overhead when 
thread-safe access is not needed; also, as you yourself describe, a 
given class may have a large number of mutation points where thread 
safety is needed in order to make the whole class thread-safe, but 
client code may actually access the instance(s) of that class in only a 
small number of places.

Rather than designing classes that are relatively inefficient, one can 
limit the implementation of thread-safety to the few places where the 
class instance(s) are actually used by client code, saving work and 
program overhead.

Pete
0
Peter
4/28/2010 1:26:31 AM
Michal, perhaps unrelated but FYI, I remember to have noticed once 
http://msdn.microsoft.com/en-us/library/ms668265(v=VS.100).aspx 
(SynchronizedCollection<T>) but I'm not sure now about the actual need...

Peter will likely provide better help if this collection could be of some 
usefullness depending on what you are trying to do. Interesting design 
thread...
--
Patrice
 


0
Patrice
4/28/2010 11:06:37 AM
Thanks for info Patrice, but it's not only about some List<> data, is about 
any data class might contain - and Editor class might also require access to 
more members. Anyway, I've solved this, but it's far from being nice ...

I've made one class:
		
public void AddObject(string name, object newObj)
{
  objects.Add(name, newObj);
}

public object Get(string name)
{
  Debug.Assert(objects.ContainsKey(name));
  return objects[name];
}

Dictionary<string, object> objects =  new Dictionary<string, object>();

and one interface:

public interface ILockableDataAccess
{
  DataAccess LockAndGetData();
  void Unlock();
}

So every class with lockable access to data provides LockAndGetData and 
Unlock functions and in DataAccess object it returns required objects. It's 
boring, not safe and requires lot of TYPING (sorry for my English in last 
post) and converting between object and my types. But only solution I have 
now ... 

To answer Peter's question:
>>In general, classes like that are not thread-safe. Why do you think 
yours should be?

Generally my program constantly generates some graphical data for other 
input devices in separate thread and it allows user to change them anytime. 
So I need thread safe access to edit and generate methods of different 
classes.

0
Utf
4/28/2010 5:23:02 PM
Sorry, here is the DataAccess class complete:

	public class DataAccess
	{
		public void AddObject(string name, object newObj)
		{
			objects.Add(name, newObj);
		}

		public object Get(string name)
		{
			Debug.Assert(objects.ContainsKey(name));
			return objects[name];
		}

		Dictionary<string, object> objects = 
			new Dictionary<string, object>();
	}
0
Utf
4/28/2010 5:25:01 PM
Michal wrote:
> [...]
> To answer Peter's question:
>>> In general, classes like that are not thread-safe. Why do you think 
> yours should be?
> 
> Generally my program constantly generates some graphical data for other 
> input devices in separate thread and it allows user to change them anytime. 
> So I need thread safe access to edit and generate methods of different 
> classes.

Non-sequitur.  The fact that you need thread-safe access to the data 
doesn't mean that the data types themselves need to be thread-safe.  The 
List<T>, Queue<T>, and many other .NET classes are not thread-safe, and 
yet I use them in a thread-safe way in multi-threaded code on a regular 
basis.  The same thing can be true for your own types.

That said, you seem set on doing things the hard way, so I suppose that 
will have to do.

Pete
0
Peter
4/29/2010 6:34:00 AM
Peter, I don't think it's safe to e.g. add some item in one thread to 
List<Whatever> and to read all the items from this List<Whatever> in another 
thread (that's what I do). So I'm sure, it's required to use thread safe 
access to my ClassToChange.
0
Utf
4/30/2010 5:12:01 AM
Michal wrote:
> Peter, I don't think it's safe to e.g. add some item in one thread to 
> List<Whatever> and to read all the items from this List<Whatever> in another 
> thread (that's what I do). So I'm sure, it's required to use thread safe 
> access to my ClassToChange.

No one, least of all me, is disputing that.  The question is whether you 
have a need to build thread-safety into the object itself.

The problem you are asking for help with is a consequence of your 
apparent desire to have a specific class manage the object used for 
locking: the class that you want to operate on in a thread-safe manner.

But, if you would simply forget trying to make that class thread-safe, 
and instead require that clients of the class access it with their own 
thread-safe behavior, the problem you're asking for help with just goes 
away.  The "lock" statement becomes completely sufficient for the need.

Pete
0
Peter
4/30/2010 5:27:23 AM
Yes, I see your point and this discussion is really helping me. But I use 
this class in two different threads - one is changing it and second is using 
it...  Anyway maybe you think about using it like this:
....
lock (editedObject)
{
//change it
}

and in my second thread also
lock (editedObject)
{
//use it
}

Yes, that might be possible - but also when I create attribute for the 
List<AnyDataClass> data e.g.:

List<AnyDataClass> Data { get { return data } }

But there's no way to assure object is locked, when accessing this data, is 
there?
0
Utf
4/30/2010 11:24:01 AM
Reply:

Similar Artilces:

How do I get SQL data to show CRLF instead of question marks?
When I query my SQL database from Excel (currently 2007) I have some fields that have carriage-return-line-feed characters and tab characters. These show as square question marks. How can I make the CRLF and TAB characters show up properly (without having to manually edit 5000 rows)? ...

How do I tell Excel to insert data from a cell 4 to the left?
Hi there, Here's the situation. I have a bunch of game prices in cells I8:I15. In cells B8:B15 are the names of these games. I have a cell that gives me the highest price [=MAX(I8:I15)] but instead of showing the price, I want it to show the name of the game. But I don't want to have to enter the name myself, I want Excel to do this automatically so if the prices change it can update itself. Is this possible? [Or does it even make any sense? ;)] Thanks in advance for any help (: Cheers, Jake. Try this... =INDEX(B8:B15,MATCH(MAX(I8:I15),I8:I15,0)) Note that i...

Users mailbox locked because server will not purge data
We have a user who tried to send an email with a 38 MB attachment (after repeatedly instructing her that we have a 3 MB attachment limit) which caused her account to not allow her to send or receive emails since she had gone over her mailbox limits. She moved the email from her Sent Items to her Deleted Items and then emptied her Deleted Items folder. The user is in one of our remote offices. When she checks her folder size, her Local Data only shows the size of her mailbox as 160 KB but when we look on System Manager it still shows her mailbox size as 38 MB. She emptied her deleted items fold...

How to write into Excel from Access 2007
I used to update Excel spreadsheets from Access with update and append queries. Now that I am with Office 2007 it seems that this feature is not allowed anymore. Is there an option to turn off or on? Thanks in advance for your help. Open the query and then click on External Data and you will see Excel as an option in the Export section. -- Build a little, test a little. "Catherine" wrote: > I used to update Excel spreadsheets from Access with update and append queries. > Now that I am with Office 2007 it seems that this feature is not allowed > an...

in vba for access how do i get the day of the week for a date field?
in vba for access how do i get the day of the week for a date field? You mean Monday, Tuesday,... Dim myDate As Date myDate = DateSerial(2005, 12, 25) MsgBox Format(myDate, "dddd") or the day portion of the date? Dim myDate As Date myDate = DateSerial(2005, 12, 25) MsgBox Day(myDate) Daniel wrote: > > in vba for access how do i get the day of the week for a date field? -- Dave Peterson ...

Restoring data to Exchange
Hello, We are trying to restore our exchange data after doing a successful Active Directory domain rename. Since Exchange is on a domain controller, we were forced to remove it to complete the domain rename. So, we used ntbackup to backup all of the data. Now, we are trying to restore the data, but we get the following message: <!-- Begin Message --> Unable to restore Exchange data to HHNSRVR\Microsoft Information Store\First Storage Group, check the application event log for more information <!-- End Message --> As it says, we looked in the event log and found this: <!-- B...

vlookup excel and access...
assuming i have this code, is possible to use this vlookup withnthe adta into mdb access?... old scenario: Private Sub TextBox25_Change() Dim CODICE As Integer Select Case Me.TextBox25 Case "" Me.TextBox4 = "" Case 1 To 8 CODICE = Val(Me.TextBox25) Me.TextBox4 = Application.WorksheetFunction.VLookup _ (CODICE, Worksheets("TABELLA").Range("Q2:R9"), 2, False) Case Else Call MULTI_LINE_BOX End Select End Sub new scenario: Inested column Q and R in excel i have created a mdb into: \\my server\myserverdir\USER.MDB and into this mdb have inserte a table U...

Sending binary data via a GET or POST REST call
Hello Everyone, I'm creating a program that will use a REST interface to send a binary file to the server but I'm really not sure how to do that. I know how to do the REST call but how do I send binary data? The documentation says I will send it as file_data=<raw_binary_data> in my GET request. I'm using the HTTPWebRequest() and HTTPWebResponse() classes to do this from the client. Can anyone help? Also, is the process much different to send via POST? Can anyone point me in the right direction? Thanks! Anthony Small Correction: The method is actually O...

How do I view Pivot Table source data file and field names?
I'd like information on how you can view the name/reference for the source data of a Pivot Table. For Example, in MS Access and Cognos Impromptu you can go to SQL view and see where data in a Query is coming from. It's easy to find the source of formulas in Excel, using the Audit Toolbar. I'd like a way to quickly view the file name (whether an Excel file or external source) and field names that were used to create the Pivot Table. chocolate2346 Wrote: > I'd like information on how you can view the name/reference for the > source > data of a Pivot Table. Fo...

Sharing vs. Delegate Access
Can anyone tell me the difference between Sharing (email, calendars,folders) vs. Delegate and delegate access? I can't find anything comparing the two!! Help! Sharing is just that - you share your folders with others. Delegates have 'send on behalf of' permission and can accept meetings on your behalf. -- Diane Poremsky [MVP - Outlook] Outlook Tips: http://www.outlook-tips.net/ Outlook & Exchange Solutions Center: http://www.slipstick.com Outlook Tips by email: dailytips-subscribe-request@lists.outlooktips.net EMO - a weekly newsletter about Outlook and Exchange: EMO-...

Problem with creating two variable data table
Presently I am unable to set up a formula in a cell for two inpu variable. I have gone through EXCEL help on how to create two variabl data table but unable to do so. There may something wrong in formula. I have done the following : Inserted a formula in cell D20 which read as : D21^2+E20^2-4. Keyed in a set of inputs in same column below the cell in which formul is written i.e. D21:D26 and keyed in another set of input in same ro in the cell that is at the right of formula cell i.e. E20:J20. Always one message comes "Input cell reference is not valid". Ther must be something wro...

Drag Email into Access Form
As a way of monortoing Email useage i would like to be able to drag an email from Outlook into a memo field on an access form. Currently it only drags the header, how do i get the body of the email message dragged across as well? ...

Numbering data pairs
I have a spreadsheet which I use to plot custom contour shapes. What I am hoping for is if someone can tell me how to go about adding the following information to the graph. My xy coordinates are easy enough to display if I need to, but what I really need is to display the numbered point. ie point xy1 should display 1, point xy2 should display 2, etc... I played around with this for a while and couldn't figure it out and the help file was, well, no help at all. Maybe I'm just dumb as a brick but I just figure out the answer. If anyone can help I'd be most obliged. Thanks AJ...

Recommendations on concurrent validation against xsd, while deserializing
Hi all I have a scenario, where I need to validate incoming XML against an XSD, and deserialize it (if valid). This is going to happen quite often (concurrently on a server), and I need to make it as effecient as possibly (that is, not do anything obviously wrong/slow). The xsd is quite large, so the validating operation is potentially timeconsuming (as is the deserialization). I understand that I should be able to 1) create an XmlSchemaSet 2) create an XmlReaderSettings (using the SchemaSet) 3) create an XmlReader (using the settings) 4) create an XmlSerializer 5) pass the XmlReader to the...

Rearrange sheet data
I need some help to get my data rearranged in my sheet. My spreadsheet contains Item Numbers and Customer Data. Column C to ? contains Customer specific information..Location...etc.. Col A Col B Col C:? Item # Customer Customer Specific information. 123 ABC Could be C:D or C:JJ 123 DEF 123 GHI 456 ABC 456 DEF I would like to rearrange the data to the following columns: Col A Col B 123 ABC Customer Specific info. C:? DEF GHI 456 ABC DEF One Item number could have 1 Customer or could have 1000...

data extraction / cleansing a string column in a workbook
I have a data extraction / cleansing problem. A computer help desk system has ticket information with textual detail placed in a field called 'Comments'. This data has been extracted to Excel spreadsheets for the last few months. I cannot know exactly where the 'Comments' column may be in each spreadsheet, however I know that the ending column location for each row is 'BA'. We need to extract phone numbers and extensions out of this data. Phone numbers can be 10 digit telephone numbers such as: 123-123-1234 or 1231231234. The 10 digit telephone numbers can have ...

Chart data series background color
How do I change the background color for the data series? I want a bar chart to display the bars with a blue color. When a number in the data series is negative, I want the bar representing the negative number to be red. On the Format Data Series window on the Patterns tab, I have checked the box that says "Invert if negative." Now when negative, the bar color is white. I can't find where to set the background color to red. You can select a different background colour to format the column. There will be a pattern showing in the column, but this may be an acceptable opti...

linked dbf tables have "invalid names" after conversion from Access 97 to Access 2000
We're using dbf files to bring data from another application to Access for detailed analysis and reporting. We have recently upgraded from Access 97 to Access 2000. Everything seems to have converted fine except linked dbf tables. The previous linked tables worked fine in Access 97 for several years. When you try and open the table Access 2000 reports that : " is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not to long. Even if we try and relink to the dbf files we get the same error. We have found that if we move the files t...

Access 2003
Hi All - I have encountered curious behaviour in MS Access 2003 which to me seems to be a bug. I have an application which has a sub-form used in several other main forms. The subform is used to select which records in a table will be processed by the main form, and the records are selected by clicking a checkbox. Depending on which main form is being used, the maximum number of records which can be selected in the sub-form can vary from 2 upwards. To "enforce" this limit, I have the following code in the Before Update event of the checkbox, to cancel the selection if the user ...

Public folder Access #7
On my exchange 2003 server while i try to access public folder i get an error message "The object is no longer available.Press F5 to refresh to display and try again. ID NO:80040e19 Exchange system manager." On client there is an error message" Unable to display the folder. This folder cannot be opened because there is a configuration problem on the server. Contact your Microsoft Exchange Server Administrator for assistance." Based on the ID NO we have checked the number of settings such as 1) There is only 1 website configured (Virtual Server).The defaul...

How does access search records in a query
When you join two tables, and one table has a million records while the other has 2000, how does access search for each join type. Which join type will run the fastest. Does access actually look through 1 million records on some of the join types. If the data with the 1 million records is a linked table would that effect the speed of the query. Does access run the query on my pc or the server where the large table resides. The oracle tables are in another state. Will this have a significant effect on performance. I tried creating a pass through query, but I got a 936 error message. I ...

OWA Access #6
What settings do I need to change in IIS so users get prompted to enter their details when login to OWA. At the moment OWA opens the mailbox of the loged in user by default. Im running Exchange 2003 clustered. There are a few things that you can do. While you can remove integrated authentication, I would suggest enabling Forms Based Authentication. MSExchange has two good articles on items surrounding FBA: http://www.msexchange.org/pages/search.asp?query=fba Bob "Lazo Basic" <l_basic.Nospam.hotmail.com> wrote in message news:uKqiyJLeFHA.3712@TK2MSFTNGP09.phx.gbl...

frustrations with Access 2006
is anyone else frustrated with the number of time, when editing a project..., Access 2006 crashes, leaving behind a corrupt, un-repairable file (or somtimes just a corrupt form, never-the-less: frustrating)? short of going back to an earlier version of the program, does any one have ANY suggestions? thanks in advance... mark "Mark Kubicki" <mark.kubicki@verizon.net> wrote in message news:u7Pv4lHDIHA.4880@TK2MSFTNGP03.phx.gbl... > is anyone else frustrated with the number of time, when editing a > project..., Access 2007 crashes, leaving behind a corrupt, un-re...

hiding private appointments?
i want to filter out my private appointments so i can display/print only my public appointments. how do i set up a filter to HIDE only my private appointments? ...

Export from Access
I built an Access database which to export the daliy (new) figures to Excel to the desktop. One of the queries is for pulling all the information for a Credit Manager (CM). I then need to link this data to a summary spreadsheet. So each day I want to go to my database, pick the CM's data, export and replace the old info with the new, and keep the links I have created when I exported the first one. When I exported the first, I linked it to a number of spreadsheets. Any thoughts? I get an error telling me that It cannot expand the named range. If I rename it then I would have to r...