multithreading - Starting and Stopping loop from thread c# -
so big deal need solve. have visual c# application. in application users enter data , click execute. when click execute core method starts in new thread, in thread , method 1 loop. using method invoker sending updates userform loop doing. e.g. updating progressbar in every cicle.
progressbar1.invoke((methodinvoker) delegate { progressbar1.value += 1; });
i got requirement add button in userform stops loop in thread , shows has been done yet. not quiting application not stopping processes or ever need jump thread , stop loop.
i thinking add public class public methods called stop_loop.cs. hoping when start program or execute core method in new thread jump class , set cancel = false, , if click on stop button jump class , set cancel true. in end @ beggining of every cicle in loop in thread check if cancel true. if is, stop loop , move end of execution.
like this. unfortunately cannot seem access class core function. not visual studio offering me option. how can ?
namespace textboxes { public class stop_loop { public bool is_canceled; public void set_canceled(bool state) { this.is_canceled = state; } public bool get_canceled() { return this.is_canceled; } } }
you should use cancellationtoken. here sample calculating factorial:
static void main(string[] args) { cancellationtokensource canceltokensource = new cancellationtokensource(); cancellationtoken token = canceltokensource.token; task task1 = new task(async () => await factorial(5, token)); task1.start(); console.writeline("type y break loop:"); string s = console.readline(); if (s == "y") canceltokensource.cancel(); console.readline(); } static async task factorial(int x, cancellationtoken token) { int result = 1; (int = 1; <= x; i++) { if (token.iscancellationrequested) { console.writeline("canceled"); return; } result *= i; console.writeline("factorial of {0} equals {1}", i, result); } }
Comments
Post a Comment