【发布时间】:2013-03-25 16:16:48
【问题描述】:
我注意到在我的任务管理器中我有这个应用程序的多个副本 - 虽然不占用任何 CPU 资源。
我知道我一定做错了什么,所以我问集体......
这是经过消毒的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace AnalyticsAggregator
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
bool onlyInstance = false;
Mutex mutex = new Mutex(true, "AnalyticsAggregator", out onlyInstance);
if (!onlyInstance)
{
return;
}
"Do stuff with the database"
GC.KeepAlive(mutex);
}
catch (Exception e)
{
EventLog eventlog = new EventLog("Application");
eventlog.Source = "AnalyticsAggregator";
eventlog.WriteEntry(e.Message, EventLogEntryType.Error);
}
}
}
}
}
我有其他不是互斥体/单例的控制台应用程序表现出相同的行为,我做错了什么?我假设某种类型的处置......
谢谢
【问题讨论】:
-
你里面为什么有
GC.KeepAlive(mutex)? -
我将您的代码复制并粘贴到 Visual Studio 中,并将
"Do Stuff"行替换为长Thread.Sleep(100000)。它按预期工作,只有一个应用程序实例正在运行。您能否发布可以重现问题的代码以及有关您的环境的更多信息? -
我见过然后使用的例子有 GC.KeepAlive(mutex);这是错的吗?
-
在
GC.KeepAlive(object)(msdn.microsoft.com/en-us/library/…) 的 MSDN 文档中,看起来只有在调用可能挂在指定对象上的非托管代码时才应该使用它。您是否在“Do stuff with the database”代码中使用了任何 COM 代码或非托管 DLL? -
@feralin 不,只是 TableAdapter 调用。我们目前使用 TableAdapters 作为我们的 DAL。