-2

I tried a lot: Thread, DoWork, Async Await, but I got the error:

System.InvalidOperationException: 'Cross-thread operation not valid: Control 'combo' accessed from a thread other than the thread it was created on.'

Here is my code:

 public void ggggg()
    {
        var Names = combo.Text;
        string[] strArray = Regex.Split(Names, " - ");
        var port = Convert.ToString(strArray[0]);
        if (port == "")
        {
            MessageBox.Show("Please Selcet ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        else
        {

            MessageBox.Show("Done", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }


     private void BtnNames_Click(object sender, EventArgs e)
     {
    Thread y = new Thread(delegate () { ggggg(); });
       y.Start();

     }  

Another part of the code:

var Names = this.Invoke(new MethodInvoker(delegate { combo.Text = combo.Text.Text + ""; }));;

2 Answers2

0

Not sure if I understood you correctly, but you may try out this:

public string ggggg(string Names)
{
    string[] strArray = Regex.Split(Names, " - ");
    return Convert.ToString(strArray[0]);
}


public async void BtnNames_Click(object sender, EventArgs e)
{
    var names = combo.Text;
    var port = await Task.Run(() => ggggg(names));

    if (port == "")
    {
        MessageBox.Show("Please Selcet ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
        MessageBox.Show("Done", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
Welcor
  • 2,431
  • 21
  • 32
0

I just add one code before If and work perfect thanks guys

public string ggggg(string Names)
{
string[] strArray = Regex.Split(Names, " - ");
return Convert.ToString(strArray[0]);
}
public async void BtnNames_Click(object sender, EventArgs e)
{
var names = combo.Text;
var port = await Task.Run(() => ggggg(names));
await Task.Factory.StartNew(() => // I add this code

if (port == "")
{
    MessageBox.Show("Please Selcet ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    MessageBox.Show("Done", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

}