Thursday, February 12, 2015

Task (Lab Assignment)



namespace Zau_Task_Lab_2_10_15
{

    //Lab Assignment: Due Tuesday Feb 10.
    //Use the following Task constructor
    //public Task(Action<Object> action, Object state)
    //This constructor allows you to pass a paremeter of type Object to the method
    //Write a method that takes a parameter (like the number of random odds to display
    //and run the method in a task using The Task constructor and the TaskFactory.

    public partial class Form1 : Form
    {
        Random rand = new Random();

        public Form1()
        {
            InitializeComponent();
        }


        private void btnDisplayOddRandomValues_Click(object sender, EventArgs e)
        {

            int num;
            int.TryParse(txtNumberOfOddNumbers.Text, out num);
            if (num != 0)
            {
                //create an Action delegate
                Action<Object> action = DisplayOddRandomNumbers;
                Task t = Task.Factory.StartNew(action, num);
            }
            else
                MessageBox.Show("Please enter a limit to display");
           
        }


        private void DisplayOddRandomNumbers(Object state)
        {
           int count = (int)state;
            int counter = 1;
            do
            {
                int num = rand.Next();
                if (num % 2 != 0)
                {
                    //richTextBox1.AppendText(counter + "    " + num + "\n");
                    SetText(counter + "  " + num, richTextBox1);

                    //scroll down automaically
                    //rtb.ScrollToCaret();
                    counter++;
                }
            } while (counter <= count);

        }
        //============================================
        private delegate void RichTextBoxHandler(string s, RichTextBox rtb);

        private void SetText(string s, RichTextBox rtb)
        {
            if (rtb.InvokeRequired)
            {
                //create a delegate object
                RichTextBoxHandler handler = SetText;
                Invoke(handler, s, rtb);
            }
            else
            {
                rtb.AppendText(s + "\n");
                //scroll down automaically
                rtb.ScrollToCaret();
            }
        }
    }
}
        //============================================

No comments:

Post a Comment