i have code
thread thread1 = new thread(this.dosomething1); thread thread2 = new thread(this.dosomething2); thread1.start(); thread2.start(); i need first thread finishes kill other immediately. note thread not kind runs while can not use static variable telling thread stop. thread end first?
ideally you'd want use cancellation token or static variable cancel thread safely.
if decide use cancellationtoken/tokensource:
var tokensource = new cancellationtokensource(); var token = tokensource.token; ... static void dosomething1or2(cancellationtoken token, cancellationtokensource tokensource) { //do other work here //since said neither of tasks looping, put //you'd want cancel thread if(token.iscancellationrequested) return; // or token.throwifcancellationrequested(); //do more stuff here tokensource.iscancellationrequested = true; } if dosomething method looping check boolean @ beginning or end of each loop see whether other thread completed. technique similar cancellationtoken.
if(otherthreadisactive && originalcondition) { //do stuff here } if can't wait iteration finish, or can't use cancellation token, i'd suggest reading this thread on aborting. best not use unless it's absolutely necessary.
best way: use cancellation token/tokensource
next best way: use sort of boolean dictate when terminate
Comments
Post a Comment