Метод не вызывается - PullRequest
       19

Метод не вызывается

0 голосов
/ 22 декабря 2018

Я пишу код для приложения Windows на c #, у меня есть 2 Class, 1 - это класс GUI, где я объявляю события и делегаты для метода ShowLog (). Следующий класс, который похож на внутренний класс, где у меня есть всеопределение методов, которые собираются на вызовы из класса GUI.Моя проблема в том, что я хочу получить доступ к некоторым методам класса GUI из внутреннего класса, используя делегаты и события.Так как это сделать.

   namespace Linux_ScriptRunner
  {
  public delegate void MyDel(object str);   
 public partial class LinuxScriptRunner : Form
   {
     public event MyDel MyEvent; 

    public void pqr(object str)
    {

        MyEvent(str);
    }




  private void btnSendCommand_Click(object sender, EventArgs e)
    {
        lstcmd =txtBxCmdLine.Text;           
        if (!lstcmd_list.Contains(lstcmd))
            lstcmd_list.Add(txtBxCmdLine.Text);
        else
        {
            lstcmd_list.Remove(lstcmd);
            lstcmd_list.Add(lstcmd);
        }
        count++;            
        lstcmdbtn.Enabled = true;            
        try
        {
            isButtonEnable = false;
            EnableDishableButton();
            string serverIPS = string.Empty;
            ListView.SelectedIndexCollection indexes= this.lstVwServerList.SelectedIndices;
            foreach (int index in indexes)
                serverIPS += "||" + lstVwServerList.Items[index].Text;

            if (serverIPS != "")
            {                 

                    System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(myButtonExcutionForCommand));
                    th.IsBackground = true;
                    th.Start(txtBxCmdLine.Text.Trim() + serverIPS);
                    lstLastAct.Items.Add(" => " + txtBxCmdLine.Text + " on " + serverIPS);
                    txtBxCmdLine.Text = String.Empty;
                    this.lstVwServerList.SelectedItems.Clear();
             //   txtBxCmdLine.Text = String.Empty;
               // this.lstVwServerList.SelectedItems.Clear();
            }
            else
            {
                MessageBox.Show("Select Ip for IP List \n ");
            }


        }
        catch (Exception ex)
        {
            Program.WriteExceptionLog(ex);
        }

    }




public void ShowLog(object s1)
    {
        string status = ((string)s1);
        try
        {
            if (richtxtBxResult.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowLog), status);                  
            }                
            else
            {                      
                richtxtBxResult.Text += Environment.NewLine + status;
                richtxtBxResult.SelectionStart = richtxtBxResult.Text.Length;
                richtxtBxResult.ScrollToCaret();
                richtxtBxResult.Refresh();                   

            }
        }
        catch (Exception ex)
        {
            Program.WriteExceptionLog(ex);
        }
    }





 private void myButtonExcutionForCommand(object commandAndServerIPS)
    {            
            try
            {
                string[] sep = {"||"};
                string[] temp = ((string)commandAndServerIPS).Split(sep, StringSplitOptions.None);
               int i = 1;
               while (i < temp.Count())
                {

                    ShowLog(temp[0] + " is executing for " + temp[i]);
                    toolStripStatusLabel1.Text = "Command Executing ... ";
                 script_runner.ExcuteCommand(temp[i], temp[0]," ");                     
                   //ShowLog("");
                  toolStripStatusLabel1.Text = " command executed Successfully... ";
                    i++;
                // ShowLog(temp[i]);
                 ShowLog("\n\n -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- \n\n");

               }

            }
            catch (Exception ex)
            {

                MessageBox.Show("Fill Column Name !!!");
               //richtxtBxResult.Text = "Im here exception_mybuttonec";
                ShowLog(ex.Message);
                Program.WriteExceptionLog(ex);
            }
            isButtonEnable = true;
            EnableDishableButton();           

    }   


    }
    }

    }



 2nd file class.......


    namespace LinuxScriptRunner
    {

  class scriptRunner
        {

      public string ExcuteCommand(String serIp, string cmd,string serDet)
      {      
        int port;
        string un=String.Empty;
        string pwd=string.Empty;
        string os=String.Empty;


        LinuxScriptRunner lsr = new LinuxScriptRunner();
       lsr.MyEvent += new MyDel(lsr.ShowLog);
   System.Threading.Thread th1 = new System.Threading.Thread(new             System.Threading.ParameterizedThreadStart(lsr.pqr));
      th1.IsBackground = true;
       th1.Start("hi"); 




    }
    }

Здесь в коде класс LinuxSriptRunner, который является моим классом GUI, имеет событие и делегат, и я хочу получить доступ к событию из класса b, используя событие класса GUI.Я надеюсь, что вы получили мои очки

1 Ответ

0 голосов
/ 24 декабря 2018

Я понял фон вашего вопроса следующим образом: бэкэнд-класс публикует событие регистрации, где он сообщает о своем прогрессе или другой информации, не зная, как это отображается.Класс GUI подписывается на это событие и делает все необходимое.Вот как то так (только набросок!):

public delegate void LoggingDelegate(string str);

public partial class Gui : Form
{
    public void ShowLog(string status)
    {
        try
        {
            if (richtxtBxResult.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowLog), status);
            }
            else
            {
                richtxtBxResult.Text += Environment.NewLine + status;
                richtxtBxResult.SelectionStart = richtxtBxResult.Text.Length;
                richtxtBxResult.ScrollToCaret();
                richtxtBxResult.Refresh();
            }
        }
        catch (Exception ex)
        {
            Program.WriteExceptionLog(ex);
        }
    }

    public void RunBackend()
    {
        var backend = new BackendClass();
        backend.LoggingEvent += ShowLog;
        Task.Run(() => backend.SomeAction());
    }
}

public class BackendClass
{
    public event LoggingDelegate LoggingEvent;

    public void SomeAction()
    {
        // ...
        LoggingEvent?.Invoke("Log output");
        // ...
    }
}
...