C # Thread Доступ из события кнопки - PullRequest
0 голосов
/ 06 июня 2018

Пожалуйста, помогите мне добавить задержку в метод Continues ().

namespace NetworkUtilities
{
    public partial class Form1 : Form
    {
        Thread th1;

        public Form1()
        {
            InitializeComponent();

            th1 = new Thread(Continues);


        } 


        private void Continues()
        {

            try
            {
                for (int j = 0; j < 4; j++)
                {

                    Ping myping1 = new Ping();

                    PingReply reply1 = myping1.Send(txtIpDns.Text, 4000);
                    rtextPingResult.AppendText("\nReply from " + reply1.Address + ": " + "bytes=32" + " time=" + reply1.RoundtripTime + "ms TTL " + reply1.Options.Ttl);
                    Thread.Sleep(500);



                }

            }
            catch (Exception ex)
            {
            }

        }

        private void btnPing_Click(object sender, EventArgs e)
        {
            try
            {
                Form1 fm = new Form1();
                btnPing.Text = "Waiting.....";
                btnPing.Enabled = false;
                rtextPingResult.Clear();
                //int packetSize = int.Parse(txtPacketSize.Text);
                Ping myping = new Ping();
                PingReply reply = myping.Send(txtIpDns.Text, 4000);



                rtextPingResult.AppendText("Pinging " + txtIpDns.Text + " [" + reply.Address + "]" + " with 32 bytes of data:");

                if (reply != null)
                        {


                            th1.Start();




                    rtextPingResult.BackColor = Color.Green;
                    btnPing.Enabled = true;
                    btnPing.Text = "Ping";
                    //t1.Abort();

                }



            }

            catch (Exception ex)
            {
                rtextPingResult.Text = "";

                //rtxtResult.AppendText("Error"+ex.InnerException.ToString);
                rtextPingResult.BackColor = Color.Red;
                rtextPingResult.AppendText("Error : Please check the IP address or DNS type Correctly or Check the Network" +"\n" +ex.Message);
                //MessageBox.Show(ex.ToString());
                btnPing.Enabled = true;
                btnPing.Text = "Ping";
            }
        }

1 Ответ

0 голосов
/ 06 июня 2018

Вы не объяснили проблему, но я предполагаю, что вы хотите, чтобы изменение цвета и т.д. происходило после Continues окончания?

Вы можете сделать это следующим образом

namespace NetworkUtilities
{
    public partial class Form1 : Form
    {
        Thread th1;

        public Form1()
        {
            InitializeComponent();

            th1 = new Thread(Continues);


        } 


        private void Continues()
        {

            try
            {
                for (int j = 0; j < 4; j++)
                {

                    Ping myping1 = new Ping();

                    PingReply reply1 = myping1.Send(txtIpDns.Text, 4000);
                    rtextPingResult.AppendText("\nReply from " + reply1.Address + ": " + "bytes=32" + " time=" + reply1.RoundtripTime + "ms TTL " + reply1.Options.Ttl);
                    Thread.Sleep(500);



                }

                Invoke((MethodInvoker) delegate {
                     rtextPingResult.BackColor = Color.Green;
                     btnPing.Enabled = true;
                     btnPing.Text = "Ping";
               });

            }
            catch (Exception ex)
            {
            }

        }

        private void btnPing_Click(object sender, EventArgs e)
        {
            try
            {
                Form1 fm = new Form1();
                btnPing.Text = "Waiting.....";
                btnPing.Enabled = false;
                rtextPingResult.Clear();
                //int packetSize = int.Parse(txtPacketSize.Text);
                Ping myping = new Ping();
                PingReply reply = myping.Send(txtIpDns.Text, 4000);



                rtextPingResult.AppendText("Pinging " + txtIpDns.Text + " [" + reply.Address + "]" + " with 32 bytes of data:");

                if (reply != null)
                        {


                            th1.Start();




                    //t1.Abort();

                }



            }

            catch (Exception ex)
            {
                rtextPingResult.Text = "";

                //rtxtResult.AppendText("Error"+ex.InnerException.ToString);
                rtextPingResult.BackColor = Color.Red;
                rtextPingResult.AppendText("Error : Please check the IP address or DNS type Correctly or Check the Network" +"\n" +ex.Message);
                //MessageBox.Show(ex.ToString());
                btnPing.Enabled = true;
                btnPing.Text = "Ping";
            }
        }

Он меняет цвет и т. Д., Когда цикл в другом потоке заканчивается, обратите внимание, что он использует Invoke, потому что вы не можете изменить элементы пользовательского интерфейса из другого потока, поэтому Invoke делает это внутри потока пользовательского интерфейса.

Кстати, избегайте

            catch (Exception ex)
            {
            }

, это просто укусит вас, потому что вы не будете знать, что происходит что-то плохое.Вы ХОТИТЕ знать, когда происходят плохие вещи, чтобы вы могли их исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...