multithreading - How to cancel execution of a long-running async task in a C# Winforms app -
i'm quite inexperienced c# programmer , need on managing flow of program. winformapp asks multiple user inputs , uses them establish serial communication device in order make measurements. measurements made in async method takes 20 minutes run. i'm using
void main() { //setup } private void button1_click(object sender, eventargs e) { await measurements(); //plot results } private async task measurements() { while(true){ //make measurements await task.delay(120000); //make measurements, present data in ui form. //return if done } }
now need make button enables user cancel measurements in order change input or parameter , restart measurements. added "cancel"-button.
private void button7_click(object sender, eventargs e) { textbox64.enabled = true; button6.enabled = true; button5.enabled = true; textbox63.enabled = true; button3.enabled = true; trackbar1.enabled = true; timer.enabled = true; button7.enabled = false; cleardata(); // measurement.stop(); }
now not know how manage flow of program. have tried make try-catch
structure in button1_click()
, throw exception button7_click
, doesn't through button1_click()
.
tried run measurements()
on new thread. thread not have access 70-ish ui items on main form.
, wont sink low trying goto.
what need advice on how program in situation in order control of application , not compromise flow of program risky stuff exceptions , goto.
if want cancel actual task midway through need @ using cancellationtokensource , passing cancellation token async method.
this microsoft documentation on has example near bottom , this blog on showing progress bar , allowing cancellation. second article has overview:
cancellation controlled cancellationtoken structure. expose cancellation tokens in signature of cancelable async methods, enabling them shared between task , caller. in common case, cancellation follows flow:
- the caller creates cancellationtokensource object.
- the caller calls cancelable async api, , passes cancellationtoken cancellationtokensource (cancellationtokensource.token).
- the caller requests cancellation using cancellationtokensource object (cancellationtokensource.cancel()).
- the task acknowledges cancellation , cancels itself, typically using cancellationtoken.throwifcancellationrequested method.
to make app respond cancel request need check cancellation token regularly in long running method , respond accordingly if cancellation has been requested.
Comments
Post a Comment