Can I lock(something) on one line in C#?

Will the _otherThing field below be protected by the locks?

class ThreadSafeThing { private readonly object _sync = new object(); private SomeOtherThing _otherThing; public SomeOtherThing OtherThing { get { lock(_sync) return _otherThing; } } public void UpdateOtherThing(SomeOtherThing otherThing) { lock(_sync) _otherThing = otherThing; } }

-------------Problems Reply------------

Yes.

This is not related to lock. C# programs are expressed using statements. Using {} groups multiple statements as a block. A block can be used in the context where a single statement is allowed. See C# language specification section 1.5.

This construction:

lock(_sync) _otherThing = otherThing;

...is the same as this construction:

lock(_sync)
{
_otherThing = otherThing;
}

So yes, the assignment of _otherThing is protected by the lock.

Yes, it will be protected because the _sync object doesn't change.

Edit: The usage of the lock you have here is almost certainly not what you meant, as detailed in several other answers in this thread.

As far as I know

lock(_sync)
_otherThing = otherThing;

is the same as

lock(_sync) _otherThing = otherThing;

is the same as

lock(_sync)
{
_otherThing = otherThing;
}

Which is similar to

if(something)
_otherThing = otherThing;

which is the same as

if(something)
{
_otherThing = otherThing;
}

(And by similar I mean similar in syntax, not in function. if is not the same as lock of course :p)

Actually you can use { } even without a lock, if or anything similar to group statements.

Your code is not thread safe, as your dealing with references.

Unless the only thing your lock is preventing is the return of the reference to your object (which is threadsafe without a lock see section 5.5 of the C# language spec) then you will not make changes to the _otherThing threadsafe.

You would need to make your mutators and accessors threadsafe in this instance (by locking around changes and reads of your object).

That will work. Single statements and block statements are pretty much always interchangeable in the C# syntax (except with method bodies and such).

However, it may not even be necessary to do the lock at all. If you want to prevent the property from being changed while other changes are made, then yes. If SomeOtherThing is a value type (struct), you will also need to lock it.

If you chose to not use a lock, you will need to declare the field volatile if you want to make sure your changes are visible in other threads immediately.

Category:c# Views:0 Time:2009-08-14

Related post

  • my mouse pointer is frozen or locked in a straight line 2014-04-09

    My mouse pointer is frozen or locked in a straight line horizontal state, making it inoperapable. It can be moved only from side to side, in a straight line. No movement up or down at all. What can I do to resolve this? Thanks for any assistance prov

  • locks up when on line watching video streaming and also on some app. on facebook 2012-03-11

    in some apps on line i lock up video streaming and other apps on facebook. also had to remove windows media player to get any video to work at all ..... on line i use explorer and firefox both and they lock up --------------Solutions------------- Hi

  • why am i not able to make connections can,t access facebook computor locks up when on line frequently 2013-02-28

    trying to access facebook right now won,t conect earlyer same thing happend some times on home page just freezes --------------Solutions------------- Hi, 1) Is the issue specific to Facebook website? 2) Do you get any error message? 3) Have you made

  • Sqlite Database is Locked In Command line(adb shell)+Android 2010-08-13

    I builded Sqlite database in android application. First i builded main_category table in Sqlite Manager.And then i export that file to my application's raw folder. My Export file is .sql file. That it is here. CREATE TABLE "main_category" ("_id" INTE

  • How can I prevent Visual Studio from locking the xml documentation files in the bin directory? 2009-07-22

    My visual studio solution includes a web application and a unit test application. My web application uses log4net. I want to be able to use msbuild from the command-line to build my solution. However, whenever I build the solution from the command-li

  • Relative performance of swap vs compare-and-swap locks on x86 2011-03-17

    Two common locking idioms are: if (!atomic_swap(lockaddr, 1)) /* got the lock */ and: if (!atomic_compare_and_swap(lockaddr, 0, val)) /* got the lock */ where val could simply be a constant or an identifier for the new prospective owner of the lock.

  • What steps should i follow to find the root cause of a table getting locked in mysql? 2011-04-14

    One of the table in mysql DB is getting locked. Please let me know the steps that i should follow to find the root cause behind it i.e. who is locking the table and when ? Thanks, Sachin --------------Solutions------------- First, check that the tabl

  • How much memory locked in a process 2011-04-23

    Using getrlimit(RLIMIT_MEMLOCK), one can get the allowed amount of locked memory a process can allocate (mlock() or mlockall()). But how to retrieve the currently locked memory amount ? For example, there's no information returned by getrusage(). Und

  • Java thread dump: BLOCKED thread without "waiting to lock -" 2011-08-15

    I'm having difficulties in understanding the thread dump I got from jstack for a Spring MVC web application running on Tomcat 6 (java 1.6.0_22, Linux). I see blocking threads (that cause other threads to wait) which are blocked themselves, however th

  • what is the purpose of session.lock method in Hibernate 2011-11-13

    I am going through lock method of hibernate. I did not get what we are trying to achieve through this method. p1 = (Person)session. get(Person.class,1);// person name is scott here // here peson name got update to henry by anothet thread session. loc

  • Continue audio playback when iPhone is locked like iPod App 2012-01-19

    I need to continue the playback even when the user locks the phone. I've seen some solution over the internet, but none of them seem to work, such as: AudioSessionSetActive(true); // Set up audio session, to prevent iPhone from deep sleeping, while p

  • Lock (not put to sleep) laptop on lid close 2013-10-05

    There doesn't appear to be an easy way to do this. Any ideas on how to make Windows lock but not go to sleep when a laptop lid is closed? --------------Solutions------------- (sorry - double post) It is for Windows 7. I don't know if it works in W8.

  • Toolbar locking no longer works 2012-08-05

    Since the last Microsoft automatic updates, the toolbars in IE 8 & IE 9 don't stay where I lock them as they used to. I lock them on one line and they move as I browse. How can I get them to stay where I lock them --------------Solutions---------

  • Media Center Locks Up during playback 2013-06-27

    I have a gigabyte motherboard (MA69-S2H I think) )with onboard everything. 4gb of RAM. 64bit windows7 When playing netflix, streaming movies from my other computer, watching recorded TV, listening to music, viewing a slideshow, really anything in Med

  • Yahoo toolbars won't stay locked 2014-06-19

    The yahoo toolbar won't stay locked on the same line as the menu bar. I do NOT have Google toolbar installed. --------------Solutions------------- Hi, I don't have the Yahoo toolbar installed on my XP machine... I will install it and get back to you.

  • Locking toolbars in IE9 rearranges them, why??? 2015-02-01

    I loaded the Bing Toolbar and repositioned it to share the line above to give me more screen real estate. If I close IE9 or lock the Toolbars, the Bing toolbar repositions itself to the original location. What gives? Is IE9 not ready for prime time?

  • Security risks of an un-encrypted connection across an international WAN? 2009-04-15

    The organisation for which I work has an international WAN that connects several of its regional LANs. One of my team members is working on a service that receives un-encrypted messages directly from a FIX gateway in Tokyo to an app server in London,

  • C++: optimizing member variable order? 2009-05-21

    I was reading a blog post by a game coder for Introversion and he is busily trying to squeeze every CPU tick he can out of the code. One trick he mentions off-hand is to "re-order the member variables of a class into most used and least used." I'm no

  • Disallowing creation of the temporary objects 2009-05-27

    While debugging crash in a multithreaded application I finally located the problem in this statement: CSingleLock(&m_criticalSection, TRUE); Notice that it is creating an unnamed object of CSingleLock class and hence the critical section object g

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.082 (s). 11 q(s)