gpt4 book ai didi

c# - Thread.abort() 和 Thread.join() 在 c# windows 应用程序中花费很长时间

转载 作者:行者123 更新时间:2023-12-02 05:28:41 26 4
gpt4 key购买 nike

在我的 C# Windows 应用程序中,

我有两个按钮导出和取消。

在我的导出按钮中,这里我将 sql 数据表导出到 .csv 文件。它在线程下运行。

thrThreadExportProcess = new Thread(new ThreadStart(startExport));
thrThreadExportProcess.Start();
thrThreadExportProcess.IsBackground = true;

当它的导出过程正在运行时,用户点击取消按钮我正在中止线程,然后加入线程并删除导出的文件。

当它加入线程时,应用程序会挂起一段时间,然后它会运行。

我的问题是为什么它会挂断一段时间。

这里是取消按钮的部分代码。

if (thrThreadExportProcess.IsAlive)
{
thrThreadExportProcess.Abort();
thrThreadExportProcess.Join();
File.Delete(csvPath);
}

请提供您宝贵的建议。

最佳答案

Thread.Abort 不保证任何事情,应该避免。为什么它在这种特定情况下挂起取决于 startExport 方法中的代码。

来自 Thread.Abort on msdn :

The thread is not guaranteed to abort immediately, or at all. This situation can occur if a thread does an unbounded amount of computation in the finally blocks that are called as part of the abort procedure, thereby indefinitely delaying the abort. To wait until a thread has aborted, you can call the Join method on the thread after calling the Abort method, but there is no guarantee the wait will end.

这是关于 Create and Terminate Threads 的文档

关于c# - Thread.abort() 和 Thread.join() 在 c# windows 应用程序中花费很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12703650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com