0

I have 2 button click events.

void Button1_click(...)
{
    //Do somethings
    Foo();
}

void Button2_Click(...)
{
    //Do somethings
    Foo();
}

The function Foo() take more than 1 minutes to finished.

When I click on button1, and after that I click button2. How can I stop Foo() in Button1_click and run only Foo() on Button2_click?

tinhve
  • 51
  • 1
  • 4
  • Well, for starters, you shouldn't be running a minute long operation in the UI thread; you won't be *able* to click another button if you do that. You'll need to do that work asynchronously. – Servy Jun 12 '15 at 16:55
  • But I need able to update my list view item on runtime. How can I do that? – tinhve Jun 12 '15 at 16:57
  • 1
    That depends on what the non-UI operation is, and how you go about making it asynchronous. There are lots of ways of scheduling UI work from a non-UI thread, and different ones will be best in different contexts. – Servy Jun 12 '15 at 16:58
  • The way you've asked this appears to be an [XY problem](http://xyproblem.info/); you're asking about how to fix an attempted solution instead of how to address the underlying problem itself. – Shotgun Ninja Jun 12 '15 at 17:21
  • 1
    @ShotgunNinja yeah, I just want to how to fix or how to do that by any way. I got my answer from StepanKobzey. :) – tinhve Jun 12 '15 at 19:02

1 Answers1

2

You should run Foo on separate thread, and invoke update on ui thread once its complete as well as use cancelation token to stop given operation at any time. Similar post is here How to update the GUI from another thread in C#?

Community
  • 1
  • 1