gpt4 book ai didi

带有 filewatcher 的 c# windows 服务

转载 作者:太空宇宙 更新时间:2023-11-03 11:24:16 26 4
gpt4 key购买 nike

第一次发布长期读者。

我在 Windows 窗体应用程序中构建了一个工作文件观察器,在将其移动到 Windows 服务之前 100% 正常运行,现在我收到两个单独的问题。此文件观察器读取平面文件以进行行更新 (lastwrite),删除/重新创建文件 (streamwriter),最后解析强类型数据集,然后上传到 SQL 服务器。(这是我的第一个 Windows 服务)问题:
1. filewatcher 中的双重事件触发器对服务的影响是否与表单应用程序不同?
2. 如果我调用的类没有问题,有人知道为什么线程会中断吗?
3. 通过 Windows 服务进行 Windows 身份验证是否存在任何已知问题?
4、谁有什么强大的windows服务调试方法?

这是我的 Windows 服务代码,在此先感谢,如果代码中出现愚蠢的错误,我深表歉意,这也是我第一次制作 Windows 服务。

    FileMonitor m_FileMonitor;
public WindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread myThread = new Thread(DoTheWork);
myThread.Start();
}
catch
{

}

}
void DoTheWork()
{
m_FileMonitor = new FileMonitor(Properties.Settings.Default.PathToFileToWatch, Properties.Settings.Default.PathToErrorLog);
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}

最佳答案

为了调试,请确保您的项目类型是 Windows 应用程序,然后使用:

[DllImport("kernel32")]
static extern bool AllocConsole();

private static void Main(string[] args)
{
var service = new MyService();
var controller = ServiceController.GetServices().FirstOrDefault(c => c.ServiceName == service.ServiceName);
if (null != controller && controller.Status == ServiceControllerStatus.StartPending)
{
ServiceBase.Run(service);
}
else
{
if (AllocConsole())
{
service.OnStart(args);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
service.OnStop();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}

如果代码因为 Windows 服务启动而运行,它将作为 Windows 服务运行。否则它将分配一个控制台,运行服务,然后在退出服务之前等待按键。您可以在此基础上测试暂停和继续。

关于带有 filewatcher 的 c# windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020512/

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