C# synchronized methods?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ASP.Net programmer

    C# synchronized methods?

    Hi,

    I have a few methods in a class that I want to synchronize (make sure they
    can't be used at the same time by multiple threads).

    As a Java programmer I just do this:
    public synchronized void methodName() {...}

    What is the C# alternative for this?

    TIA.
  • Richard Blewett [DevelopMentor]

    #2
    Re: C# synchronized methods?

    You can decorate the method with the MethodImpl attribute

    [MethodImpl(Meth odImplOptions.S ynchronized)]

    However, you can normally achieve better results with explicit acquisition on monitors only around the pieces of code that are work with shared state. Better as in less contention -> better throughput.

    Regards

    Richard Blewett - DevelopMentor



    Hi,

    I have a few methods in a class that I want to synchronize (make sure they
    can't be used at the same time by multiple threads).

    As a Java programmer I just do this:
    public synchronized void methodName() {...}

    What is the C# alternative for this?

    TIA.

    Comment

    • Brian Delahunty

      #3
      RE: C# synchronized methods?

      Just wrap the entire content of your method in a lock statement.

      E.g.

      public class MyClass
      {
      public void MyMethod()
      {
      lock(typeof(MyC lass))
      {
      // contents of method
      }
      }
      }

      Alternatively, you could do this:

      [MethodImpl(Meth odImplOptions.S ynchronized)]
      public void MyMethod()
      {
      // Contents of method
      }

      Both are not exactly the same and the second one is more like the
      synchronized keyword in Java but in general people use locks in C# as it
      gives you more fine grained control.

      Hope this helps.

      --
      Brian Delahunty
      Ireland




      "ASP.Net programmer" wrote:
      [color=blue]
      > Hi,
      >
      > I have a few methods in a class that I want to synchronize (make sure they
      > can't be used at the same time by multiple threads).
      >
      > As a Java programmer I just do this:
      > public synchronized void methodName() {...}
      >
      > What is the C# alternative for this?
      >
      > TIA.
      >[/color]

      Comment

      • ASP.Net programmer

        #4
        Re: C# synchronized methods?

        "Richard Blewett [DevelopMentor]" <richardb@NOSPA Mdevelop.com> wrote in
        news:ODlgGL$mFH A.3288@TK2MSFTN GP09.phx.gbl:
        [color=blue]
        > You can decorate the method with the MethodImpl attribute
        >
        > [MethodImpl(Meth odImplOptions.S ynchronized)]
        >
        > However, you can normally achieve better results with explicit
        > acquisition on monitors only around the pieces of code that are work
        > with shared state. Better as in less contention -> better throughput.
        >
        > Regards
        >
        > Richard Blewett - DevelopMentor[/color]

        Thank you Richard. I think I'll use the lock code that Brian posted, only
        because I am more comfortable with that and it is immediately obvious what
        it does.

        Thanks for the quick reply.

        Comment

        • ASP.Net programmer

          #5
          RE: C# synchronized methods?

          =?Utf-8?B?QnJpYW4gRGV sYWh1bnR5?=
          <BrianDelahunty @discussions.mi crosoft.com> wrote in
          news:E485EDFB-1D9E-4EEB-818C-652E3BDB92A2@mi crosoft.com:
          [color=blue]
          > Just wrap the entire content of your method in a lock statement.
          >
          > E.g.
          >
          > public class MyClass
          > {
          > public void MyMethod()
          > {
          > lock(typeof(MyC lass))
          > {
          > // contents of method
          > }
          > }
          > }
          >
          > Alternatively, you could do this:
          >
          > [MethodImpl(Meth odImplOptions.S ynchronized)]
          > public void MyMethod()
          > {
          > // Contents of method
          > }
          >
          > Both are not exactly the same and the second one is more like the
          > synchronized keyword in Java but in general people use locks in C# as
          > it gives you more fine grained control.
          >
          > Hope this helps.
          >[/color]

          It sure helps!

          I'll use the lock code, because that looks better IMO and I'll know what
          I wrote in a few months from now. ;)

          Thanks for the quick reply.

          Comment

          • Richard Blewett [DevelopMentor]

            #6
            RE: C# synchronized methods?

            Be careful with the lock keyword.

            It doesn't take a timeout - infinite waits and multithreading are a nasty source of deadlocks. It would be better to use Ian Griffiths' TimedLock



            Regards

            Richard Blewett




            =?Utf-8?B?QnJpYW4gRGV sYWh1bnR5?=
            <BrianDelahunty @discussions.mi crosoft.com> wrote in
            news:E485EDFB-1D9E-4EEB-818C-652E3BDB92A2@mi crosoft.com:
            [color=blue]
            > Just wrap the entire content of your method in a lock statement.
            >
            > E.g.
            >
            > public class MyClass
            > {
            > public void MyMethod()
            > {
            > lock(typeof(MyC lass))
            > {
            > // contents of method
            > }
            > }
            > }
            >
            > Alternatively, you could do this:
            >
            > [MethodImpl(Meth odImplOptions.S ynchronized)]
            > public void MyMethod()
            > {
            > // Contents of method
            > }
            >
            > Both are not exactly the same and the second one is more like the
            > synchronized keyword in Java but in general people use locks in C# as
            > it gives you more fine grained control.
            >
            > Hope this helps.
            >[/color]

            It sure helps!

            I'll use the lock code, because that looks better IMO and I'll know what
            I wrote in a few months from now. ;)

            Thanks for the quick reply.

            Comment

            • ASP.Net programmer

              #7
              RE: C# synchronized methods?

              "Richard Blewett [DevelopMentor]" <richardb@NOSPA Mdevelop.com> wrote in
              news:eMOVql$mFH A.3256@tk2msftn gp13.phx.gbl:
              [color=blue]
              > Be careful with the lock keyword.
              >
              > It doesn't take a timeout - infinite waits and multithreading are a
              > nasty source of deadlocks. It would be better to use Ian Griffiths'
              > TimedLock
              >
              > http://www.interact-sw.co.uk/iangblo...retimedlocking
              >
              > Regards
              >
              > Richard Blewett
              > http://www.dotnetconsult.co.uk/weblog
              > http://www.dotnetconsult.co.uk[/color]

              Hi Richard,

              I use similair code like this in the lock blocks:

              dsWSCompany1.Cl ear();
              daWSCompany.Sel ectCommand.Comm andText = "select * from
              company where name like '" + companyName + "'" + " order by name";
              daWSCompany.Fil l(dsWSCompany1) ;
              return dsWSCompany1;

              It's for an ASP.Net project. It's not very likely that this takes too
              much time and the select command itself will time-out anyway.

              Thanks for the warning, though. ;)

              Comment

              • Octavio Hernandez

                #8
                Re: C# synchronized methods?

                Hi, Brian!

                The synchronized keyword in Java can be used not only as a method
                'attribute', but also as a statement:

                synchronized (object) { statement; }

                I used to think the creators of C# decided to retain in the language only
                this synchronization construct as more 'general'. I had not seen before the
                use of the MethodImplOptio ns.Synchronized option.

                Regards - Octavio

                "Brian Delahunty" <BrianDelahunty @discussions.mi crosoft.com> escribió en el
                mensaje news:E485EDFB-1D9E-4EEB-818C-652E3BDB92A2@mi crosoft.com...[color=blue]
                > Just wrap the entire content of your method in a lock statement.
                >
                > E.g.
                >
                > public class MyClass
                > {
                > public void MyMethod()
                > {
                > lock(typeof(MyC lass))
                > {
                > // contents of method
                > }
                > }
                > }
                >
                > Alternatively, you could do this:
                >
                > [MethodImpl(Meth odImplOptions.S ynchronized)]
                > public void MyMethod()
                > {
                > // Contents of method
                > }
                >
                > Both are not exactly the same and the second one is more like the
                > synchronized keyword in Java but in general people use locks in C# as it
                > gives you more fine grained control.
                >
                > Hope this helps.
                >
                > --
                > Brian Delahunty
                > Ireland
                >
                > http://briandela.com/blog
                >
                >
                > "ASP.Net programmer" wrote:
                >[color=green]
                >> Hi,
                >>
                >> I have a few methods in a class that I want to synchronize (make sure
                >> they
                >> can't be used at the same time by multiple threads).
                >>
                >> As a Java programmer I just do this:
                >> public synchronized void methodName() {...}
                >>
                >> What is the C# alternative for this?
                >>
                >> TIA.
                >>[/color][/color]


                Comment

                • Richard Blewett [DevelopMentor]

                  #9
                  RE: C# synchronized methods?

                  Thats not the issue I'm talking about.

                  void Method1()
                  {
                  lock(foo)
                  {
                  lock(bar)
                  {
                  // do something requiring foo and bar
                  }
                  }
                  }

                  void Method2()
                  {
                  lock(bar)
                  {
                  lock(foo)
                  {
                  // do something requiring foo and bar
                  }
                  }
                  }

                  If these two methods execute concurrently you have a reasonable chance of deadlock (a deadly embrace). The problem is the two threads will just halt and never continue so you are in an unrecoverable position that can't even supply any diagnostics. If you had a timeout in those lock statements you have the ability to realise that you cannot acquire a lock for some reason and that you have a deadlock situation. These can then be be logged and so diagnosed later. In some situation you can simply retry the operation and it succeeds as the other thread will have finished.

                  Regards

                  Richard Blewett - DevelopMentor



                  "Richard Blewett [DevelopMentor]" <richardb@NOSPA Mdevelop.com> wrote in
                  news:eMOVql$mFH A.3256@tk2msftn gp13.phx.gbl:
                  [color=blue]
                  > Be careful with the lock keyword.
                  >
                  > It doesn't take a timeout - infinite waits and multithreading are a
                  > nasty source of deadlocks. It would be better to use Ian Griffiths'
                  > TimedLock
                  >
                  > http://www.interact-sw.co.uk/iangblo...retimedlocking
                  >
                  > Regards
                  >
                  > Richard Blewett
                  > http://www.dotnetconsult.co.uk/weblog
                  > http://www.dotnetconsult.co.uk[/color]

                  Hi Richard,

                  I use similair code like this in the lock blocks:

                  dsWSCompany1.Cl ear();
                  daWSCompany.Sel ectCommand.Comm andText = "select * from
                  company where name like '" + companyName + "'" + " order by name";
                  daWSCompany.Fil l(dsWSCompany1) ;
                  return dsWSCompany1;

                  It's for an ASP.Net project. It's not very likely that this takes too
                  much time and the select command itself will time-out anyway.

                  Thanks for the warning, though. ;)

                  [microsoft.publi c.dotnet.langua ges.csharp]

                  Comment

                  Working...