LomidzeAlex LomidzeAlex - 3 years ago 136
C# Question

C# - Break Loop from another button

In my program i'm starting

for loop
, I want to break this for loop using another
For example:

private void button1_Click(object sender, EventArgs e)
for( int i = 0; i < var; i++)
//doing something

And using second button break loop,

private void button2_Click(object sender, EventArgs e)
//breaking loop;

Need help :)

Answer Source

You cannot do that, because the loop in button1_Click event handler will be holding the UI thread. Your user interface will not respond to any event, showing hourglass icon, until the loop is over. This means that button2_Click cannot be entered until button1_Click has completed.

You need to replace the long-running loop from the event handler with something that runs outside the UI thread. For example, you can use Tasks, which can be cancelled using CancellationToken (related Q&A).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download