Monday 14 March 2016

Task.Delay Example in c#

private void button4_Click(object sender, EventArgs e)
        {


            if (textBox6.Text != "" && textBox7.Text != "" && textBox8.Text != "" && textBox9.Text != "" )
            {
                // 11:00:00
                var DailyTime = "" + textBox8.Text + ":" + textBox7.Text + ":" + textBox6.Text + "";
                var timeParts = DailyTime.Split(new char[1] { ':' });

                var dateNow = DateTime.Now; // current time
                var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
                           int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2])); // user input time
                TimeSpan ts;
                if (date > dateNow)
                    ts = date - dateNow;
                else
                {
                    // date = date.AddDays(1);
                    date = date.AddHours(12);
                    ts = date - dateNow;
                    if (date == dateNow)
                        //  ts = date - dateNow;
                        ts = dateNow - date;
                }
                string msg = textBox9.Text;

                //waits certan time and run the code
                Task.Delay(ts).ContinueWith((x) => SomeMethod(msg));

                Console.Read();
                MessageBox.Show("Reminder added succesfully !!");
                textBox6.Text = "";
                textBox7.Text = "";
                textBox8.Text = "";
                textBox9.Text = "";
            }
            else
            {
                MessageBox.Show("All Fields Are Mandatory !!");
            }
        }

static void SomeMethod(string reminderMsg)
        {
          //  MessageBox.Show("" + reminderMsg + "" + "@:" + DateTime.Now.ToString());
          //  MessageBox.Show(new Form() { TopMost = true }, "" + reminderMsg + "" + "@:" + DateTime.Now.ToString());
            TopMostMessageBox.Show("" + reminderMsg + "" + "  Reminder set at :"+ DateTime.Now.TimeOfDay.ToString()+"", "Reminder !!!", MessageBoxButtons.OK);
         
        }

No comments:

Post a Comment