このコードでメモリ リークが発生しているようです。これはコンソール アプリであり、いくつかのクラス (WorkerThread) を作成し、それぞれが指定された間隔でコンソールに書き込みます。これには Threading.Timer が使用されるため、コンソールへの書き込みは別のスレッドで実行されます (TimerCallback は ThreadPool から取得した別のスレッドで呼び出されます)。さらに複雑なことに、MainThread クラスは FileSystemWatcher の Changed イベントにフックします。test.xml ファイルが変更されると、WorkerThread クラスが再作成されます。
ファイルが保存されるたびに (WorkerThread、したがってタイマーが再作成されるたびに)、タスク マネージャーのメモリが増加します (メモリ使用量、場合によっては VM サイズも)。さらに、.Net Memory Profiler (v3.1) では、WorkerThread クラスの Undisposed Instances が 2 増加します (ただし、.Net Memory Profiler には検出に苦労するバグがあったことを読んだので、これは危険かもしれません)。破棄されたクラス。
とにかく、ここにコードがあります-誰かが何が悪いのか知っていますか?
編集: クラスの作成を FileSystemWatcher.Changed イベント ハンドラーから移動しました。つまり、WorkerThread クラスは常に同じスレッドで作成されます。静的変数にいくつかの保護を追加しました。また、何が起こっているかをより明確に示すためにスレッド情報を提供し、Timer の使用と明示的な Thread の使用を交換してきました。ただし、メモリはまだリークしています。メモリ使用量は常にゆっくりと増加し (これは単にコンソール ウィンドウの余分なテキストが原因ですか?)、ファイルを変更すると VM サイズが増加します。コードの最新バージョンは次のとおりです。
編集これは、主に、書き込み時にコンソールがメモリを使い果たすという問題のようです。明示的に記述されたスレッドがメモリ使用量を増加させるという問題はまだあります。以下の私の答えを見てください。
class Program
{
private static List<WorkerThread> threads = new List<WorkerThread>();
static void Main(string[] args)
{
MainThread.Start();
}
}
public class MainThread
{
private static int _eventsRaised = 0;
private static int _eventsRespondedTo = 0;
private static bool _reload = false;
private static readonly object _reloadLock = new object();
//to do something once in handler, though
//this code would go in onStart in a windows service.
public static void Start()
{
WorkerThread thread1 = null;
WorkerThread thread2 = null;
Console.WriteLine("Start: thread " + Thread.CurrentThread.ManagedThreadId);
//watch config
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "../../";
watcher.Filter = "test.xml";
watcher.EnableRaisingEvents = true;
//subscribe to changed event. note that this event can be raised a number of times for each save of the file.
watcher.Changed += (sender, args) => FileChanged(sender, args);
thread1 = new WorkerThread("foo", 10);
thread2 = new WorkerThread("bar", 15);
while (true)
{
if (_reload)
{
//create our two threads.
Console.WriteLine("Start - reload: thread " + Thread.CurrentThread.ManagedThreadId);
//wait, to enable other file changed events to pass
Console.WriteLine("Start - waiting: thread " + Thread.CurrentThread.ManagedThreadId);
thread1.Dispose();
thread2.Dispose();
Thread.Sleep(3000); //each thread lasts 0.5 seconds, so 3 seconds should be plenty to wait for the
//LoadData function to complete.
Monitor.Enter(_reloadLock);
thread1 = new WorkerThread("foo", 10);
thread2 = new WorkerThread("bar", 15);
_reload = false;
Monitor.Exit(_reloadLock);
}
}
}
//this event handler is called in a separate thread to Start()
static void FileChanged(object source, FileSystemEventArgs e)
{
Monitor.Enter(_reloadLock);
_eventsRaised += 1;
//if it was more than a second since the last event (ie, it's a new save), then wait for 3 seconds (to avoid
//multiple events for the same file save) before processing
if (!_reload)
{
Console.WriteLine("FileChanged: thread " + Thread.CurrentThread.ManagedThreadId);
_eventsRespondedTo += 1;
Console.WriteLine("FileChanged. Handled event {0} of {1}.", _eventsRespondedTo, _eventsRaised);
//tell main thread to restart threads
_reload = true;
}
Monitor.Exit(_reloadLock);
}
}
public class WorkerThread : IDisposable
{
private System.Threading.Timer timer; //the timer exists in its own separate thread pool thread.
private string _name = string.Empty;
private int _interval = 0; //thread wait interval in ms.
private Thread _thread = null;
private ThreadStart _job = null;
public WorkerThread(string name, int interval)
{
Console.WriteLine("WorkerThread: thread " + Thread.CurrentThread.ManagedThreadId);
_name = name;
_interval = interval * 1000;
_job = new ThreadStart(LoadData);
_thread = new Thread(_job);
_thread.Start();
//timer = new Timer(Tick, null, 1000, interval * 1000);
}
//this delegate instance does NOT run in the same thread as the thread that created the timer. It runs in its own
//thread, taken from the ThreadPool. Hence, no need to create a new thread for the LoadData method.
private void Tick(object state)
{
//LoadData();
}
//Loads the data. Called from separate thread. Lasts 0.5 seconds.
//
//private void LoadData(object state)
private void LoadData()
{
while (true)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("Worker thread {0} ({2}): {1}", _name, i, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(50);
}
Thread.Sleep(_interval);
}
}
public void Stop()
{
Console.WriteLine("Stop: thread " + Thread.CurrentThread.ManagedThreadId);
//timer.Dispose();
_thread.Abort();
}
#region IDisposable Members
public void Dispose()
{
Console.WriteLine("Dispose: thread " + Thread.CurrentThread.ManagedThreadId);
//timer.Dispose();
_thread.Abort();
}
#endregion
}