为什么创建这些线程不释放内存?
why creating these threads don't free memory?
我有这样一个代码:
class Engine
{
private static Thread f_thread;
private static System.Timers.Timer timeWatch;
public static void Start()
{
try
{
timeWatch = new System.Timers.Timer(30000);
timeWatch.Elapsed += FolderMonitor;
timeWatch.AutoReset = true;
timeWatch.Enabled = true;
}
catch (Exception ex)
{
// catch error
}
}
public static void FolderMonitor(object source, ElapsedEventArgs e)
{
f_thread = new Thread(FileScan);
f_thread.Start();
}
public static void FileScan()
{
if (timeWatch != null)
{
timeWatch.Stop();
}
try
{
// some operations
}
catch (Exception ex)
{
// catch error
}
timeWatch.Start();
}
}
在 .NET Core 2.2 Windows 远程机器上 运行 服务。
如果我在 运行ning 1 周后检查内存,它会不断增长。
它似乎没有释放线程分配的内存(某种内存泄漏)。
但如果我在线程的 FileScan 函数中“什么都不做”,它也会长大(较小,但 id 会)。
怎么了? GC 不应该自动释放它吗?
静态对象和属于这些对象的变量(即您创建的线程和 运行)不会在 C# 中进行垃圾回收。
要进行垃圾回收的线程必须属于非静态对象,必须停止并清除所有引用(mythread = null)。
我在使用线程时遇到了同样的问题,用 C# 编写了一个音频流专用服务器。
当我发现泄漏时,我不得不重新思考并重写大部分代码。 :)
我有这样一个代码:
class Engine
{
private static Thread f_thread;
private static System.Timers.Timer timeWatch;
public static void Start()
{
try
{
timeWatch = new System.Timers.Timer(30000);
timeWatch.Elapsed += FolderMonitor;
timeWatch.AutoReset = true;
timeWatch.Enabled = true;
}
catch (Exception ex)
{
// catch error
}
}
public static void FolderMonitor(object source, ElapsedEventArgs e)
{
f_thread = new Thread(FileScan);
f_thread.Start();
}
public static void FileScan()
{
if (timeWatch != null)
{
timeWatch.Stop();
}
try
{
// some operations
}
catch (Exception ex)
{
// catch error
}
timeWatch.Start();
}
}
在 .NET Core 2.2 Windows 远程机器上 运行 服务。 如果我在 运行ning 1 周后检查内存,它会不断增长。
它似乎没有释放线程分配的内存(某种内存泄漏)。
但如果我在线程的 FileScan 函数中“什么都不做”,它也会长大(较小,但 id 会)。 怎么了? GC 不应该自动释放它吗?
静态对象和属于这些对象的变量(即您创建的线程和 运行)不会在 C# 中进行垃圾回收。
要进行垃圾回收的线程必须属于非静态对象,必须停止并清除所有引用(mythread = null)。
我在使用线程时遇到了同样的问题,用 C# 编写了一个音频流专用服务器。
当我发现泄漏时,我不得不重新思考并重写大部分代码。 :)