Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Skipping locked section already in use

Skipping locked section already in use

Scheduled Pinned Locked Moved C#
questionjson
27 Posts 7 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Sentenryu

    this "chat" is a submission to my university, i can't use a database and need to user a server application that communicates witch tcp/ip (if i can use a database, this wouldn't be a problem :) ) in theory it works with the static class, the problem is that i'm afraid it's not safe, what happens if two users connected (so, two threads) request the server to add a new user, then the server call the Add method 2 times simultaneously, the Add method writes a XML file and then reads it again (yes, poor implementation, hopefully not mine). the point in making it a static class is that in this way all the threads would have access to the same list of users, but i've seen very strange comportment of this class, in the static constructor, the class instantiate and fills the list of contacts, i've put a breakpoint here and tested, for some reason, when i called the add method, the static constructor was not executed, with scared the shit out of me, everything was null, then, when the method returned (the method executed with success, even with the List null, they were able to add to it, i don't know how) then the execution point moved to the static constructor, in my breakpoint. after much test, i've found that when 2 threads call a method of this class, the secund call execute before the static constructor, i think it's a bug with my installation of visual studio, i prefer not to consider that this can occur i in a production environment, but just in case...

    I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

    P Offline
    P Offline
    PIEBALDconsult
    wrote on last edited by
    #12

    Sentenryu wrote:

    submission to my university

    If it's classwork, then considering and trying out different ways of implementing it is a good thing. :thumbsup:

    Sentenryu wrote:

    if two users connected (so, two threads)

    My understanding is that if they're in separate App Domains, then a Singleton won't help anyway -- each would have its own instance. And that would be true of a static class as well. You may need to look into a Mutex, which is sort of like the locking object, but system-wide.

    S 1 Reply Last reply
    0
    • P PIEBALDconsult

      Sentenryu wrote:

      submission to my university

      If it's classwork, then considering and trying out different ways of implementing it is a good thing. :thumbsup:

      Sentenryu wrote:

      if two users connected (so, two threads)

      My understanding is that if they're in separate App Domains, then a Singleton won't help anyway -- each would have its own instance. And that would be true of a static class as well. You may need to look into a Mutex, which is sort of like the locking object, but system-wide.

      S Offline
      S Offline
      Sentenryu
      wrote on last edited by
      #13

      now you have confused me, the console application that acts as the server is the only one who will use this class, what will be sent to the client is a xml response of their request. the threads are created in the server with a ThreadPool (subject to change, i think i'm using the wrong class, maybe i'm confusing it with java's ThreadPool...) in my understanding, all of those threads run in the App Domain of the console application, is this wrong?

      I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

      P 1 Reply Last reply
      0
      • S Sentenryu

        now you have confused me, the console application that acts as the server is the only one who will use this class, what will be sent to the client is a xml response of their request. the threads are created in the server with a ThreadPool (subject to change, i think i'm using the wrong class, maybe i'm confusing it with java's ThreadPool...) in my understanding, all of those threads run in the App Domain of the console application, is this wrong?

        I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #14

        Sentenryu wrote:

        all of those threads run in the App Domain of the console application

        Oh, yes, but then why do you have threads?

        Sentenryu wrote:

        the console application

        The main method of which is static already, so I'd likely stick with static. Hmmm... so, if I understand what you're saying, each client makes a connection to the Server and gets its own thread, which I suppose is a session, and it continues to interact with the server that way until it disconnects? I'm not sure that's a good architecture*, but not being an expert on that sort of thing, I'd better keep quiet and let others provide guidance. * I'm fairly sure that a "connectionless" technique is more robust.

        S 1 Reply Last reply
        0
        • P PIEBALDconsult

          Sentenryu wrote:

          i was thinking in replacing the static class with a singleton, you think it's a bad idea?

          Mainly I just don't see the point. Does it work as a static class? What do you think a Singleton would provide that a static class doesn't? If the users are running in different systems then they wouldn't share the Singleton anyway -- and if it's behind a Service then it's just a black box so what difference does it make to the clients? If you've read up on the Singleton Pattern, then you should know that it provides a shared instance -- if it isn't going to be shared, then it probably isn't the right tool for the job. Nor am I sure that a static class is either; I'd likely just instantiate one instance of a regular class. When I wrote a chat system, it had a database and each client connected to the database server to log in/out, get the list of users, send/get messages, etc. -- I haven't gotten around to writing a Web Service for it yet, and haven't experimented with Web Services at all for two years. But I wouldn't automatically run off and write a Singleton to hide behind the Service.

          RaviBeeR Offline
          RaviBeeR Offline
          RaviBee
          wrote on last edited by
          #15

          PIEBALDconsult wrote:

          What do you think a Singleton would provide that a static class doesn't?

          The ability for the singleton to be passed as a parameter. /ravi

          My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

          P 1 Reply Last reply
          0
          • RaviBeeR RaviBee

            PIEBALDconsult wrote:

            What do you think a Singleton would provide that a static class doesn't?

            The ability for the singleton to be passed as a parameter. /ravi

            My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #16

            Yes, but you're not supposed to do that with a Singleton -- being a Singleton means you don't have to pass it, all parts of the system know where to get it: "Provide a global point of access to the object."

            RaviBeeR 1 Reply Last reply
            0
            • P PIEBALDconsult

              Yes, but you're not supposed to do that with a Singleton -- being a Singleton means you don't have to pass it, all parts of the system know where to get it: "Provide a global point of access to the object."

              RaviBeeR Offline
              RaviBeeR Offline
              RaviBee
              wrote on last edited by
              #17

              There are cases where we can have different singletons, all of which implement an interface IFoo (for example) and a method that has accepts an IFoo parameter.  Due to separation of concerns, the method may have no idea about the existence of the concrete singletons.  For example:

              static class PrettyPrinter
              {
              public static string PrettyPrint
              (string textToBePrettyPrinted,
              IPrettyPrinterRuleProvider rulesToUse)
              {
              ...
              return prettyPrintedString;
              }
              }

              ...

              string text = "...";
              string result1 = PrettyPrinter.PrettyPrint (text, KAndRTypeFormattingRules.Instance);
              string result2 = PrettyPrinter.PrettyPrint (text, MicrosoftFormattingRules.Instance);

              /ravi

              My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

              P 1 Reply Last reply
              0
              • RaviBeeR RaviBee

                There are cases where we can have different singletons, all of which implement an interface IFoo (for example) and a method that has accepts an IFoo parameter.  Due to separation of concerns, the method may have no idea about the existence of the concrete singletons.  For example:

                static class PrettyPrinter
                {
                public static string PrettyPrint
                (string textToBePrettyPrinted,
                IPrettyPrinterRuleProvider rulesToUse)
                {
                ...
                return prettyPrintedString;
                }
                }

                ...

                string text = "...";
                string result1 = PrettyPrinter.PrettyPrint (text, KAndRTypeFormattingRules.Instance);
                string result2 = PrettyPrinter.PrettyPrint (text, MicrosoftFormattingRules.Instance);

                /ravi

                My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                P Offline
                P Offline
                PIEBALDconsult
                wrote on last edited by
                #18

                Well sure, but would you design a class to do that with and make it a Singleton? Why? I see no reason to do so. Look at, perhaps, System.StringComparer and its fields.

                RaviBeeR 1 Reply Last reply
                0
                • P PIEBALDconsult

                  Well sure, but would you design a class to do that with and make it a Singleton? Why? I see no reason to do so. Look at, perhaps, System.StringComparer and its fields.

                  RaviBeeR Offline
                  RaviBeeR Offline
                  RaviBee
                  wrote on last edited by
                  #19

                  PIEBALDconsult wrote:

                  make it a Singleton? Why?

                  For performance reasons.  I would prefer to not have to new up a concrete IPrettyPrinterRuleProvider each time I call PrettyPrinter.PrettyPrint(). /ravi

                  My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                  P J 2 Replies Last reply
                  0
                  • RaviBeeR RaviBee

                    PIEBALDconsult wrote:

                    make it a Singleton? Why?

                    For performance reasons.  I would prefer to not have to new up a concrete IPrettyPrinterRuleProvider each time I call PrettyPrinter.PrettyPrint(). /ravi

                    My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #20

                    And you don't; nor does it need to be a Singleton. It can be a static field of the class, for instance.

                    RaviBeeR 1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      And you don't; nor does it need to be a Singleton. It can be a static field of the class, for instance.

                      RaviBeeR Offline
                      RaviBeeR Offline
                      RaviBee
                      wrote on last edited by
                      #21

                      Yes, but that would cause unneccesary coupling. I'm not suggesting singletons are absolutely necessary (heck even while, for, switch and continue statements aren't!).  My point is the singleton pattern (especially when combined with Lazy<T>) allows one to write more performant and more manageable code. /ravi

                      My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                      P 1 Reply Last reply
                      0
                      • RaviBeeR RaviBee

                        Yes, but that would cause unneccesary coupling. I'm not suggesting singletons are absolutely necessary (heck even while, for, switch and continue statements aren't!).  My point is the singleton pattern (especially when combined with Lazy<T>) allows one to write more performant and more manageable code. /ravi

                        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #22

                        Ravi Bhavnani wrote:

                        that would cause unneccesary coupling.

                        I don't think so.

                        Ravi Bhavnani wrote:

                        one to write more performant and more manageable code.

                        Bullpuckey.

                        1 Reply Last reply
                        0
                        • J jschell

                          Pete O'Hanlon wrote:

                          The biggest problem with singletons lies in the fact that it reduces parallelism. As you only have a single instance present, any threaded operations must be serialized in and out of the singleton, reducing the efficiency of the threading. They can also make it harder to unit test code because it can introduce global state.

                          I don't agree. The biggest problem with singletons is incorrect usage and from that overusage. For your points... For the first problem sometime the very nature of the need dictates serialization anyways. And in other cases there are ways that can allow multiple access. As for the second problem there are trivial solutions for most problems of that nature, for example just implementing a Reset() method.

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #23

                          jschell wrote:

                          For the first problem sometime the very nature of the need dictates serialization anyways.

                          In that case, you shouldn't be parallelising the code at this point. This concern was raised specifically for the case where you have a parallel architecture that has to be throttled because of a singleton.

                          jschell wrote:

                          As for the second problem there are trivial solutions for most problems of that nature, for example just implementing a Reset() method.

                          So, we're talking about introducing a method just to get through a test; not for any other purpose. I think you misunderstood my point. I wasn't arguing that you should never use a singleton; I was just showing what the weaknesses are. If you are comfortable that you understand the pattern sufficiently well, and that you know exactly how your code is going to be used, then you can make an informed decision. If you don't know what the weaknesses are, then you can end up causing all sorts of problems for yourself.

                          *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                          "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                          CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                          J 1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            Sentenryu wrote:

                            all of those threads run in the App Domain of the console application

                            Oh, yes, but then why do you have threads?

                            Sentenryu wrote:

                            the console application

                            The main method of which is static already, so I'd likely stick with static. Hmmm... so, if I understand what you're saying, each client makes a connection to the Server and gets its own thread, which I suppose is a session, and it continues to interact with the server that way until it disconnects? I'm not sure that's a good architecture*, but not being an expert on that sort of thing, I'd better keep quiet and let others provide guidance. * I'm fairly sure that a "connectionless" technique is more robust.

                            S Offline
                            S Offline
                            Sentenryu
                            wrote on last edited by
                            #24

                            i'm just very bad in English =p there's no logical connection from the client to the server, the client just sends a request and the server responds, after the response, there's no more link between the client and the server, the threads are used so the server can serve more than one client at a time.

                            I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

                            1 Reply Last reply
                            0
                            • S Sentenryu

                              i would like to hear more about why singleton are silly... I've a case where a server application would manage a list of users, the server could add a user, getLoggedUsers, log a user in, log out a user, get a list of all users and contact one user to send a chat request (the client contacts the server about the chat request, the server alerts the target user and then the users would chat directly), to implement the functionality of the contacts list (not a simple List, sadly) i've made a static class who controls the underling List, synchronizing it with a XML file (used to serialize the list), this way, all the users contacting the server would see the same list of users. i was thinking in replacing the static class with a singleton, you think it's a bad idea? i would appreciate your opinion.

                              I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p)

                              B Offline
                              B Offline
                              BobJanova
                              wrote on last edited by
                              #25

                              They artificially restrict your ability to change your mind later, and don't really provide any benefit. You can always just instantiate one copy of an object if you only need one! If you have a need for a single static instance of some stuff, have a static reference to it.

                              static class GlobalData {
                              public static ContactListManager ContactListManager { get; private set; }

                              static GlobalData(){
                              ContactListManager = new ContactListManager("datastore.xml");
                              }
                              }

                              That way, if you discover that you want to manage disparate contacts across several data sources and therefore it shouldn't be a singleton any more, it's much easier to change. It means that if you want a temporary separate instance for some reason (e.g. importing external data), you can do so.

                              1 Reply Last reply
                              0
                              • RaviBeeR RaviBee

                                PIEBALDconsult wrote:

                                make it a Singleton? Why?

                                For performance reasons.  I would prefer to not have to new up a concrete IPrettyPrinterRuleProvider each time I call PrettyPrinter.PrettyPrint(). /ravi

                                My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                J Offline
                                J Offline
                                jschell
                                wrote on last edited by
                                #26

                                Ravi Bhavnani wrote:

                                For performance reasons.  I would prefer to not have to new up a concrete IPrettyPrinterRuleProvider

                                There is design, implementation and performance. Distinct but interrelated idioms. You would NEVER impose a design limit based solely on creating an instance. You MIGHT impose a design limit based on the work that creating an instance requires. That however is very, very rare. (I am specifically referring to creating the instance.) And I suspect for your example it does not apply. In terms of measuring (actual values) the performance of an application if you find that a specific bit of code imposes a performance bottleneck on the application (not a just a hunk of code) then you modify the implementation to correct that. If you must modify the design to correct a measured performance problem then you have a bug in the design which requires a rework of the design and implementation. The factors the lead to a redesign where the ONLY problem is a performance problem is probably very rare. Typically if someone cannot anticipate a performance problem at the design level then the design is incomplete or the designer does not have enough experience and thust the entire design is questionable.

                                1 Reply Last reply
                                0
                                • P Pete OHanlon

                                  jschell wrote:

                                  For the first problem sometime the very nature of the need dictates serialization anyways.

                                  In that case, you shouldn't be parallelising the code at this point. This concern was raised specifically for the case where you have a parallel architecture that has to be throttled because of a singleton.

                                  jschell wrote:

                                  As for the second problem there are trivial solutions for most problems of that nature, for example just implementing a Reset() method.

                                  So, we're talking about introducing a method just to get through a test; not for any other purpose. I think you misunderstood my point. I wasn't arguing that you should never use a singleton; I was just showing what the weaknesses are. If you are comfortable that you understand the pattern sufficiently well, and that you know exactly how your code is going to be used, then you can make an informed decision. If you don't know what the weaknesses are, then you can end up causing all sorts of problems for yourself.

                                  *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

                                  "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                                  CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                                  J Offline
                                  J Offline
                                  jschell
                                  wrote on last edited by
                                  #27

                                  Pete O'Hanlon wrote:

                                  In that case, you shouldn't be parallelising the code at this point. This concern was raised specifically for the case where you have a parallel architecture that has to be throttled because of a singleton.

                                  Not sure what you are referring to. I took your response to suggest that you were addressing the Singleton Pattern, and not one specific instance of that.

                                  Pete O'Hanlon wrote:

                                  So, we're talking about introducing a method just to get through a test; not for any other purpose.

                                  Yep.

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups