Home > Back-end >  Terminate function running in a thread in c#?
Terminate function running in a thread in c#?

Time:09-01

I want to terminate a function running in a thread

Thread t = new Thread(SomeFunction())
{
Background = true;
}

This someFunction() is running in background and from some other function(e.g. . CancelSomeFunction()) I have to cancel this thread t.

So I want to store something like threadId(t.ManagedThreadId()) in database and have to cancel the thread or want to use t.Abort().

I am using distributed system so I cant store thread instance in a variable to abort it in same class.

So is there any better way to get thread instance from thread id(stored in db) in C#?

Or any other way to cancel it, better if you explain with code snippet as I am new to c#.


Update

So If it can be done with cancellation token then is there any way to store token in db as there can be multiple task and we will be having multiple token for each task.

Suppose I am calling someFunction five times and I want to cancel what I clicked for the third time. Then I need to store something to cancel it(like token identifier from which I can get cancellationToken instance to call cancel() function. Is there any way to do so?

CodePudding user response:

If you want to cancel a thread then the thread needs to cooperate. Otherwise, if you want to force it, then run your code in a separate process and kill the process.

You can start a process and get its Id like this:

var p = Process.Start(new ProcessStartInfo() { FileName = "some_executable.exe" });
int id = p.Id;

Then you can save that to a database.

Later you can do this:

var p = Process.GetProcessById(id);
p.Kill();
  • Related