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. its regarding Multi-threading

its regarding Multi-threading

Scheduled Pinned Locked Moved C#
helpregexquestion
14 Posts 5 Posters 0 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.
  • J Judah Gabriel Himango

    Are you using C# 2? If so, you can use anonymous delegates to do this:

    void Foo()
    {
    int val = 5;
    string text = "blah";

    // Use an anonymous method to pass the locals to the function.
    ThreadPool.QueueUserWorkItem(delegate
    {
        OnAnotherThread(val, text);
    });
    

    }

    void OnAnotherThread(int i, string s)
    {
    MessageBox.Show(s);
    }

    Another way--the way that the C# 2 compiler implements it under the hood--is to create a class that stores the variables you want to pass to the function, then create a function in that class whose signatures matches WaitCallback. Here's an example:

    void Foo()
    {
    int val = 5;
    string text = "blah";

    HolderClass holder = new Holder(val, text);
    ThreadPool.QueueUserWorkItem(holder.OnAnotherThread);
    

    }

    class HolderClass
    {
    private int value;
    private string text;

     public HolderClass(int value, string text)
     {
         this.value = value;
         this.text = text;
     }
    
     public void OnAnotherThread(object state)
     {
          MessageBox.Show(this.text);
     }
    

    }

    Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

    M Offline
    M Offline
    Mystic_
    wrote on last edited by
    #5

    iam using VS 2003 and SDK V 1.1 its not supported in my version

    1 Reply Last reply
    0
    • J Judah Gabriel Himango

      Are you using C# 2? If so, you can use anonymous delegates to do this:

      void Foo()
      {
      int val = 5;
      string text = "blah";

      // Use an anonymous method to pass the locals to the function.
      ThreadPool.QueueUserWorkItem(delegate
      {
          OnAnotherThread(val, text);
      });
      

      }

      void OnAnotherThread(int i, string s)
      {
      MessageBox.Show(s);
      }

      Another way--the way that the C# 2 compiler implements it under the hood--is to create a class that stores the variables you want to pass to the function, then create a function in that class whose signatures matches WaitCallback. Here's an example:

      void Foo()
      {
      int val = 5;
      string text = "blah";

      HolderClass holder = new Holder(val, text);
      ThreadPool.QueueUserWorkItem(holder.OnAnotherThread);
      

      }

      class HolderClass
      {
      private int value;
      private string text;

       public HolderClass(int value, string text)
       {
           this.value = value;
           this.text = text;
       }
      
       public void OnAnotherThread(object state)
       {
            MessageBox.Show(this.text);
       }
      

      }

      Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

      M Offline
      M Offline
      Mystic_
      wrote on last edited by
      #6

      it would be a mess if i do it with global variables. it would be my last resort. if it ever is.

      J J 2 Replies Last reply
      0
      • M Mystic_

        it would be a mess if i do it with global variables. it would be my last resort. if it ever is.

        J Offline
        J Offline
        Jun Du
        wrote on last edited by
        #7

        You don't have to use global data. Instaed, you can create a wrapper class which contains your thread function and all other related methods and data members. The only constraint is that all of the methods and data members should be static. The following C++ code snippets are extracted from my CP article http://www.codeproject.com/useritems/xlogoff.asp[^]. My thread function processes lots of data within the class. One thing to note is that I used mutex to protect the data accessed by more than one thread. Here is the OnStart() in my Windows service code, which simply starts a thread:

        void OnStart(String* args[])
        {
        // Start the communication thread
        Thread *oThread = new Thread(new ThreadStart(0, &XLogoffThread::ThreadProc));
        oThread->Start();

        // some code omitted...

        }

        Here is the thread class which contains a thread function as the delegate function to ThreadStart and all other methods and data:

        public __gc class XLogoffThread
        {
        private: static String* prevSession;
        private: static String* DATA_FILE = S"session.dat";
        private: static ArrayList* baseline = new ArrayList;
        public: static Mutex * mut = new Mutex();
        private: static SnippetsCPU::ProcessAsUser *cpau = new SnippetsCPU::ProcessAsUser();
        // The ThreadProc method is called when the thread starts.

        public: static void ThreadProc()
        {
        try
        {
        // Create the session data file
        if ( !File::Exists(DATA_FILE) )
        {
        File::Create(DATA_FILE);
        }

          // Set the server to listen on port 30000
          Int32 port = 30000;
          IPAddress\* localAddr = IPAddress::Parse(S"127.0.0.1");
          TcpListener\* server = new TcpListener(localAddr, port);
          Byte bytes\[\] = new Byte\[128\];
        
          // Start listening for connections
          server->Start();
        
          // Enter the listening loop.
          while (true) 
          {
            // Perform a blocking call to accept requests.
            TcpClient\* client = server->AcceptTcpClient();            
            String\* data = 0;
        
        // Get a stream for reading and writing
        NetworkStream\* stream = client->GetStream();
        
        // Loop to receive all the data sent by the client.
        do
        {
          // Read bytes
          Int32 i = stream->Read(bytes, 0, bytes->Length);					 
          // Convert to an ASCII string.
          data = Text::Encoding::ASCII->GetStr
        
        M 1 Reply Last reply
        0
        • J Jun Du

          You don't have to use global data. Instaed, you can create a wrapper class which contains your thread function and all other related methods and data members. The only constraint is that all of the methods and data members should be static. The following C++ code snippets are extracted from my CP article http://www.codeproject.com/useritems/xlogoff.asp[^]. My thread function processes lots of data within the class. One thing to note is that I used mutex to protect the data accessed by more than one thread. Here is the OnStart() in my Windows service code, which simply starts a thread:

          void OnStart(String* args[])
          {
          // Start the communication thread
          Thread *oThread = new Thread(new ThreadStart(0, &XLogoffThread::ThreadProc));
          oThread->Start();

          // some code omitted...

          }

          Here is the thread class which contains a thread function as the delegate function to ThreadStart and all other methods and data:

          public __gc class XLogoffThread
          {
          private: static String* prevSession;
          private: static String* DATA_FILE = S"session.dat";
          private: static ArrayList* baseline = new ArrayList;
          public: static Mutex * mut = new Mutex();
          private: static SnippetsCPU::ProcessAsUser *cpau = new SnippetsCPU::ProcessAsUser();
          // The ThreadProc method is called when the thread starts.

          public: static void ThreadProc()
          {
          try
          {
          // Create the session data file
          if ( !File::Exists(DATA_FILE) )
          {
          File::Create(DATA_FILE);
          }

            // Set the server to listen on port 30000
            Int32 port = 30000;
            IPAddress\* localAddr = IPAddress::Parse(S"127.0.0.1");
            TcpListener\* server = new TcpListener(localAddr, port);
            Byte bytes\[\] = new Byte\[128\];
          
            // Start listening for connections
            server->Start();
          
            // Enter the listening loop.
            while (true) 
            {
              // Perform a blocking call to accept requests.
              TcpClient\* client = server->AcceptTcpClient();            
              String\* data = 0;
          
          // Get a stream for reading and writing
          NetworkStream\* stream = client->GetStream();
          
          // Loop to receive all the data sent by the client.
          do
          {
            // Read bytes
            Int32 i = stream->Read(bytes, 0, bytes->Length);					 
            // Convert to an ASCII string.
            data = Text::Encoding::ASCII->GetStr
          
          M Offline
          M Offline
          Mystic_
          wrote on last edited by
          #8

          thanx alot buddy. i will try it out. but one thing about ur code of class XLogoffThread. it never use those static properties in the ThreadProc(). so whats the use of those fields. i asked because thats the concept iam going to implement.

          J 1 Reply Last reply
          0
          • M Mystic_

            thanx alot buddy. i will try it out. but one thing about ur code of class XLogoffThread. it never use those static properties in the ThreadProc(). so whats the use of those fields. i asked because thats the concept iam going to implement.

            J Offline
            J Offline
            Jun Du
            wrote on last edited by
            #9

            ProcessCmd(data) and its delegates use these data. Most of the code has been omitted in the post. You might want to grab the complete code following the link in that post. Best, Jun

            G M 2 Replies Last reply
            0
            • J Jun Du

              ProcessCmd(data) and its delegates use these data. Most of the code has been omitted in the post. You might want to grab the complete code following the link in that post. Best, Jun

              G Offline
              G Offline
              Gavin Roberts
              wrote on last edited by
              #10

              why don't you just use a delegate?! public delegate void Name(object param1, object param2); private void MyMethod(object param1, object param2) { // do what you need. } then call Name n = new Name(MyMethod); // control being a listView or form etc. control.Invoke(n, new object[] { "test", "test2" });

              M 1 Reply Last reply
              0
              • M Mystic_

                it would be a mess if i do it with global variables. it would be my last resort. if it ever is.

                J Offline
                J Offline
                Judah Gabriel Himango
                wrote on last edited by
                #11

                Who said anything about globals? There are no globals in C#; everything belongs to a class. Use the second example I gave, it would work fine for you.

                Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                M 1 Reply Last reply
                0
                • J Judah Gabriel Himango

                  Who said anything about globals? There are no globals in C#; everything belongs to a class. Use the second example I gave, it would work fine for you.

                  Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                  M Offline
                  M Offline
                  Mystic_
                  wrote on last edited by
                  #12

                  i meant golab in a class. its bit vague term but i use it for public members of a class.

                  1 Reply Last reply
                  0
                  • G Gavin Roberts

                    why don't you just use a delegate?! public delegate void Name(object param1, object param2); private void MyMethod(object param1, object param2) { // do what you need. } then call Name n = new Name(MyMethod); // control being a listView or form etc. control.Invoke(n, new object[] { "test", "test2" });

                    M Offline
                    M Offline
                    Mystic_
                    wrote on last edited by
                    #13

                    yeh but annoymus delegate wont work with .Net 1.1. i have that one. there got to be other solutions for this version as well.

                    1 Reply Last reply
                    0
                    • J Jun Du

                      ProcessCmd(data) and its delegates use these data. Most of the code has been omitted in the post. You might want to grab the complete code following the link in that post. Best, Jun

                      M Offline
                      M Offline
                      Mystic_
                      wrote on last edited by
                      #14

                      i got ur point and i have already transformed my code in way u said. its doing great. thanx buddy

                      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