1
votes

In my Windows Form application I have created 2 Forms. In form 1 when I click button1, a new task will start. Inside the task I have created an instance of the form2 and show form2. I am calling the showData Method of Form2.

//Form1
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(int a1, EventArgs e);

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        Form2 form2 = new Form2();
        form2.Show();
    }
}

//Form2
public void showData(Form1 m)
{
    m.Tick += new Form1.TickHandler(test);
}

public void test(int a1,EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        for (int i = a1; i < 1000; i++)
        {
            label1.Invoke(new MethodInvoker(delegate { label1.Text = i.ToString(); }));
        }
    });
}
1
Invoke when you do anything on UI elements including new Form2()kenny
I added Invoke but it showing error message on test method in form2 like this 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.'Ram
move that code to execute on the Loaded event on the formkenny

1 Answers

1
votes

As kenny suggested i have modified the code. now it running how i am expected.

 public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                Action act1 = (() =>
                {
                    Form2 form2 = new Form2();
                    form2.StartPosition = FormStartPosition.CenterParent;
                    form2.Show();
                });
                this.BeginInvoke(act1);
            });
        }
}

// FORM2

private void Form2_Load(object sender, EventArgs e)
        {
            test(1);
        }
        public void test(int a1)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = a1; i < 1000; i++)
                {
                    label1.Invoke(new MethodInvoker(delegate { label1.Text = i.ToString(); }));
                }
            });
        }

Once again thanks Kenny