Windows Develop Bookmark and Share   
 index > Windows Forms General > put the timer on thread
 

put the timer on thread

I have placed a code in the timer to check if the PC is connected to internet every 1sec but it's causing my application to be slow..

Is everything I put in the timer is threaded? if not, how can I put it in thread to improve the performance?



Jassim Rahma
Jassim Rahma  Saturday, October 03, 2009 7:51 AM
Something's wrong with your code.  Checking anything once a second shouldn't affect the rest of your program.
JohnWein  Saturday, October 03, 2009 8:01 AM
Which timer class are you using? System.Windows.Forms.Timer or System.Threading.Timer ? How did you conclude that this is the one causing your application to slow? What are the symptoms?
The only think i understand is what i feel..
Panagiotis Kefalidis  Saturday, October 03, 2009 8:04 AM
i am not sure because I am not on the laptop now.. but I am using the control from the toolbox.
Jassim Rahma
Jassim Rahma  Saturday, October 03, 2009 8:07 AM
That's not a threaded timer.  You'll block the UI thread while the Tick event runs, that can be noticeable.

Hans Passant.
nobugz  Saturday, October 03, 2009 3:31 PM
I even tried the threaded timer but it's the same.. this is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Net;
using System.Net.Mail;

namespace The_Internet_Cafe_System
{
    public partial class frmFirstRun : Form
    {
        SqlConnection sql_connection = null;
        SqlCommand sql_command = null;
        // SqlDataAdapter sql_adapter;
        // DataTable data_table = null;
        // SqlDataReader sql_reader = null;
        // DataSet data_set = null;

        public string email_subject;
        public bool system_created = false;
        public bool internet_connected = false;

        public frmFirstRun()
        {
            InitializeComponent();
        }

        private bool is_connected()
        {
            bool connected = SystemInformation.Network;
            if (connected)
            {
                connected = false;
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT NetConnectionStatus FROM Win32_NetworkAdapter");
                foreach (System.Management.ManagementObject networkAdapter in searcher.Get())
                {
                    if (networkAdapter["NetConnectionStatus"] != null)
                    {
                        if (Convert.ToInt32(networkAdapter["NetConnectionStatus"]).Equals(2))
                        {
                            connected = true;
                            break;
                        }
                    }
                }
                searcher.Dispose();
            }
            return connected;
        }

        private void prepare_system()
        {
            activate_system();

            if (system_created == true)
            {
                create_database();
                create_tables();
                reindex_all();
            }
        }

        private void send_activation_email()
        {
            this.Cursor = Cursors.WaitCursor;

            email_subject = "Email from (TICS) user";

            string[] textLines;
            string msg;
            msg = "";
            // textLines = txtMessage.Lines;
            /*
            foreach (string line in textLines)
            {
                msg = msg + line + "<br />";
            }
             * */

            /*
            string thank_reply;
            thank_reply = "Thank you for contacting TICS support. Your feedback is valuable to us. We will read your email carefuly and reply to you as soon as possible";
            // string[] textLines;
            string thanks_msg;
            thanks_msg = "";
            // textLines = thank_reply.Lines;
            foreach (string line in textLines)
            {
                msg = msg + line + "<br />";
            }
             * */

            if (SendMail("EMAIL REMOVED", "a1b2c3d4", txtEmailAddress.Text, "TICS Support Form", "EMAIL REMOVED", email_subject, msg) && SendMail("EMAIL REMOVED", "a1b2c3d4", txtEmailAddress.Text, "TICS Support", "EMAIL REMOVED", "Thank you for your feedback", "thanls_msg"))
            {
                MessageBox.Show("Activation code was sent to your email:" + Environment.NewLine + Environment.NewLine + txtEmailAddress.Text, "Activation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("unable to send your activation email to:" + Environment.NewLine + Environment.NewLine + txtEmailAddress.Text, "Activation", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static bool SendMail(string gMailAccount, string password, string from, string displayname, string to, string subject, string message)
        {
            try
            {
                NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
                MailMessage msg = new MailMessage();
                msg.Sender = new MailAddress(from, displayname);
                msg.ReplyTo = new MailAddress(from, displayname);
                msg.From = new MailAddress(from, displayname);
                msg.To.Add(new MailAddress(to, "Jassim Rahma"));
                msg.Subject = subject;
                message = message.Replace(@"\r\n", Environment.NewLine);
                msg.Body = message;
                msg.IsBodyHtml = true;

                SmtpClient client = new SmtpClient("smtp.gmail.com");
                client.Port = 587;
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = loginInfo;
                client.Send(msg);

                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        private void create_database()
        {
            this.Cursor = Cursors.WaitCursor;

            // Assembly asm = Assembly.GetExecutingAssembly();
            // Console.WriteLine(asm.GetType().GUID.ToString());

            sql_connection = new SqlConnection("Data Source=.\\SQLEXPRESS;initial catalog=the2_internet_cafe;integrated security=true");

            try
            {
                sql_connection.Open();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        private void create_tables()
        {
        }

        private void reindex_all()
        {
        }

        private void activate_system()
        {
            this.Cursor = Cursors.WaitCursor;

            sql_connection = new SqlConnection("Data Source=.\\SQLEXPRESS;initial catalog=the_internet_cafe;integrated security=true;");
            sql_connection.Open();

            sql_command = new SqlCommand("sp_add_new_internet_cafe", sql_connection);
            sql_command.CommandType = CommandType.StoredProcedure;

            sql_command.Parameters.Add("@system_name", SqlDbType.VarChar).Value = txtInternetCafe.Text;
            sql_command.Parameters.Add("@system_telephone", SqlDbType.VarChar).Value = txtTelephone.Text;
            sql_command.Parameters.Add("@system_email", SqlDbType.VarChar).Value = txtEmailAddress.Text.Trim();
            // return status value;
            SqlParameter return_value = sql_command.Parameters.Add("@return_value", SqlDbType.Int);
            return_value.Direction = ParameterDirection.ReturnValue;
            // execute the query;
            int result_rows = sql_command.ExecuteNonQuery();

            if ((int)return_value.Value == 1010)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show("The same email address already exist.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmailAddress.Focus();
                return;
            }
            else
            {
                sql_connection.Close();

                system_created = true;

                send_activation_email();
            }
        }

        private void btnActivate_Click(object sender, EventArgs e)
        {
            // connect to internet, get hardware guid and send activation code;

            if (txtInternetCafe.Text.Trim() == "")
            {
                MessageBox.Show("Please enter internet cafe name!!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtInternetCafe.Focus();
                return;
            }

            if (txtEmailAddress.Text.Trim() == "")
            {
                MessageBox.Show("Please enter internet cafe email address!!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmailAddress.Focus();
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            timerMain.Enabled = false;

            Properties.Settings.Default.is_first_run = false;
            Properties.Settings.Default.Save();
            Properties.Settings.Default.Reload();

            prepare_system();

            if (system_created == true)
            {
                panelActivate.Visible = false;

                panelPreparing.Top = panelActivate.Top;
                panelPreparing.Left = panelActivate.Left;
                panelPreparing.Width = panelActivate.Width;
                panelPreparing.Height = panelActivate.Height;

                progressPreparing.Properties.Stopped = true;

                panelPreparing.Visible = true;
            }

            // Application.Restart();
        }

        private void frmFirstRun_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
        }

        private void frmFirstRun_Shown(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;


            
            this.Cursor = Cursors.Default;
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            if (is_connected() == true)
            {
                internet_connected = true;
                lblInternetConnection.Visible = false;
                btnActivate.Enabled = true;
            }
            else
            {
                internet_connected = false;
                lblInternetConnection.Visible = true;
                // btnActivate.Enabled = false;
                btnActivate.Enabled = true;
            }
        }

        private void backgroundWorkerMain_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void btnVerify_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            sql_connection = new SqlConnection("Data Source=.\\SQLEXPRESS;initial catalog=the_internet_cafe;integrated security=true;");
            sql_connection.Open();

            sql_command = new SqlCommand("sp_verify_activation_code", sql_connection);
            sql_command.CommandType = CommandType.StoredProcedure;

            sql_command.Parameters.Add("@system_name", SqlDbType.VarChar).Value = txtInternetCafe.Text;
            sql_command.Parameters.Add("@system_telephone", SqlDbType.VarChar).Value = txtTelephone.Text;
            sql_command.Parameters.Add("@system_email", SqlDbType.VarChar).Value = txtEmailAddress.Text.Trim();
            // return status value;
            SqlParameter return_value = sql_command.Parameters.Add("@return_value", SqlDbType.Int);
            return_value.Direction = ParameterDirection.ReturnValue;
            // execute the query;
            int result_rows = sql_command.ExecuteNonQuery();

            if ((int)return_value.Value == 1010)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show("The same email address already exist.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmailAddress.Focus();
                return;
            }
            else
            {
                sql_connection.Close();

                system_created = true;

                send_activation_email();
            }
        }
    }
}



Jassim Rahma
Jassim Rahma  Sunday, October 04, 2009 7:18 AM

What is the type of your timer? System.Timers.Timer, System.Threading.Timer or System.Windows.Forms.Timer?

If you drag the timer control form toolbox, you can see its definition in Form1.Designer.cs code. It’s System.Windows.Forms.Timer.

You’d better use the other two Timer. They are thread timer.

 

Best regards,

Ling Wang


Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
Ling Wang  3 hours 10 minutes ago

You can use google to search for other answers

Custom Search

More Threads

• Quick VS.Net/VSS Whidbey Questions
• How do I set defaults for my combo boxes?
• TreeView Node
• System Tray Icon
• ToolStrip problem
• Editing Data in a Form Using SQL
• How to get toolStrip transparent background?
• how to activate a MDI child
• GUI Prototyping and Database design
• Retrieving/removing item from toolStripDropDownButton