简体   繁体   English

多线程 | 威胁已经被清除了

[英]Multithreading | Thread was being aborted

We are running a long job (function) in 3-4 different threads.我们在 3-4 个不同的线程中运行一个很长的工作(函数)。 All running threads got successfully completed but sometimes the exception Thread was being aborted is being thrown by one of the thread which results all threads to stop.所有正在运行的线程都已成功完成,但有时导致所有线程停止的线程之一抛出异常Thread was being aborted Below is sample code for what we are actually doing in our application.下面是我们在应用程序中实际执行的示例代码。

List<Thread> lstThreads = new List<Thread>();
foreach(int 0; i < 4; i++)
{
  Thread th = new Thread(() => {
    RunLongRunningJob(i);
  });
  lstThreads.Add(th);
}
foreach (Thread th in lstThreads)
  th.Start();

We are calling rest api's, writing in files and update database records in RunLongRunningJob .我们正在调用 rest api,在RunLongRunningJob写入文件并更新数据库记录。

PS We are not using LOCKS, is this could be the reason? PS 我们没有使用 LOCKS,这可能是原因吗?

In C#, threads can not be stopped at all without side effects.在 C# 中,线程根本无法停止而不会产生副作用。 Imagine the thread has disposable items ready and - just stops.想象一下线程已准备好一次性物品并且 - 只是停止。 As a workaround, when a thread gets aborted (which you an - you should not, but you can call on the Thread object) a ThreadAbortException is generated and executed.作为一种解决方法,当一个线程中止时(您不应该这样做,但您可以调用 Thread 对象)会生成并执行 ThreadAbortException。 This allows exception handling to kick in and close file handles etc.这允许异常处理启动和关闭文件句柄等。

Ah, finally found it - this is the blog post explaining why YOU should never call Thread.Abort (ie it should not be called by application code):啊,终于找到了 - 这是解释为什么你永远不应该调用 Thread.Abort (即它不应该被应用程序代码调用)的博客文章:

http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation

This is about timing and the thread not actually executing finally properly in really bad cases.这是关于时间和线程在非常糟糕的情况下最终没有正确执行的问题。

Now, SOMETHING must find out what causes the thread to be aborted.现在,必须找出导致线程中止的原因。 This is something to check - exception details would help, including the stack trace and possible inner exception in it.这是要检查的东西 - 异常详细信息会有所帮助,包括堆栈跟踪和其中可能的内部异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM