locked
Can I pass parameters in such ways? RRS feed

  • Question

  • Hi, all

    I am a beginner in C#. And I donnt know can I pass parameters in such two ways:

    1. The first one works with ThreadPool and WaitCallBack

    public class WorkService
    {
        private string id;

        private int count;

        public ReqService(string id, int count, )
        {
             this.id = id;
             this.count = count;
         }

        public void DoWork(Object stateInfo)
        {
             ...
        }
    }

    public class SomeClass
    {
        public void SomeMethod()
        {
             ...
             WorkService workService = new WorkService("", 0);//"", 0 are the parameters to be passed
             ThreadPool.QueueUserWorkItem(new WaitCallback(workService.DoWork));
        }
    }

     

    2. The other one works with Timer and TimeCallBack

    public void someMethod

    {

        Boolean flag = true;
        Timer timer = new Timer(ChangeFlag, flag, 0, 5000);

         //As you can see, I hope the timer change the flag

         while(flag)

         {

             ...

         }

    }

    private void ChangeFlag(Object state)

    {

        Boolean flag = (Boolean) state;

        flag = false;

    }

     

    Thanks for your suggestion on my code.

    Monday, March 12, 2007 12:37 PM

Answers

  • Hi,

      you second method will not work since the bool data type is a value type, when you pass it around copies of it will be made, so the flag bool inside your while(flag) loop is a different copy of a bool to the one you modify.  You should instead make a class level member which can be accessed by both methods.

     

    Mark.

    Tuesday, March 13, 2007 1:40 AM

All replies

  • Hi,

      you second method will not work since the bool data type is a value type, when you pass it around copies of it will be made, so the flag bool inside your while(flag) loop is a different copy of a bool to the one you modify.  You should instead make a class level member which can be accessed by both methods.

     

    Mark.

    Tuesday, March 13, 2007 1:40 AM
  • Thank you!

    Mark

    Tuesday, March 13, 2007 2:25 AM