Answer the question
In order to leave comments, you need to log in
How to exit a thread (from another class) in C#?
In general, such an essence. We have a thread (Thread) that launches the Start function, and it, in turn, works in a loop and launches a function from another class - Check. We need to make terminating the flow from the Check function as easy as possible. We will have about 80 threads. You can return the value and stop with break, but the code will be confusing, because we should not have one exit point. Please advise the best solution.
class Job
{
public void Start ()
{
While(true)
{
//...иной код
new Job2().Check();
//...иной код
}
}
}
class Job2
{
public void check ()
{
//...иной код
if(a == true)
{
//здесь должен быть выход из потока.
}
//...иной код
}
}
}
Answer the question
In order to leave comments, you need to log in
It seems to me that the task was originally designed in such a way that confusing solutions are obtained. The first thought about canceling the execution of the thread was also done on the basis of CToken, but it turns out that the token must also be passed to the check method (from there we also call cancellation in this version), which I personally don’t really like.
Throwing an exception in principle should work, but the idea itself is more like some kind of hack, after all, exceptions are best used for really exceptional situations.
On the other hand, look, it turns out that the check method checks something. So it should return the result of the check (true/false). Based on the results of the check, a decision should be made whether to stop the execution or continue. It seems to me that we need to reconsider the solution of the problem so that the logic is more obvious, and not throwing exceptions in different places in the code.
How about throwing an exception, catching it in the outer loop and exiting there?
You have a mess in architecture. Describe the problem without your guesses about the implementation and it will be much easier to offer you a more adequate solution.
I do not quite understand why you need explicit flow control. Look towards Task, there are convenient mechanisms for returning values and canceling.
You can try calling the Abort method on the current thread.Thread.CurrentThread.Abort();
If it is possible to use .net 4.5, then it is best to do everything using Async constructs (unless the use of threads is justified by a special need). The normal output from the thread is passed through Invoke, only you have to store a reference to the parent thread.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question