-1

I want to start the program without suspend. For example

private void button1_Click(object sender, EventArgs e)
{            
    test();
}

protected void test()
{            
    label1.Text = "";
    for (int i = 0; i < 10; i++)
    {
        label1.Text += i;
        Thread.Sleep(500);
    }
}

When I run this program the form suspend while cycle the end. How to make so that to run function test() without suspend the form, for example to run as background?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
testesxi
  • 41
  • 1
  • 7

2 Answers2

3

You can use Asynchronous programming, so make your method async like this:

protected async Task test()
{
    label1.Text = "";
    for (int i = 0; i < 10; i++)
    {
        label1.Text += i;
        await Task.Delay(500);
    }
}

And it would be better to use it, all the way down:

private async void button1_Click(object sender, EventArgs e)
{
    await test();
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

Try the async await method (I also replaced Thread.Sleep with Task.Delay):

private async void button1_Click(object sender, EventArgs e)
{            
    await test();
}

protected async Task test()
{            
    label1.Text = "";
    for (int i=0;i<10;i++)
    {
        label1.Text += i;
        await Task.Delay(TimeSpan.FromMilliseconds(500)); //Thread.Sleep(500);
    }
}

If you are doing a lot of CPU work, you should do something like: await Task.Run(() => ...

You may find this async/await intro helpful.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109