Windows 由于 DataAdapter.Fill(),服务未启动

Windows Service not starting due to DataAdapter.Fill()

我写了一个 windows 服务,它从本地数据库获取数据并执行一个功能。为了连接到数据库,我写了下面的代码

SqlConnection connstring1;
            string conn1 = ConfigurationManager.ConnectionStrings["nameOfConnectionString"].ConnectionString.ToString();
            connstring1 = new SqlConnection(conn1);
            connstring1.Open();
            string cmd = "Select [OrderId], [VendorId], [txtPaymentMethod] , [txtPaymentStatus], [Updated_On] FROM [Postmate_ Shopping].[dbo].[tbl_Order_Master]  WHERE [txtPaymentMethod] = 'online' AND [txtPaymentStatus]= 'pending'";
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            SqlDataAdapter da1 = new SqlDataAdapter(cmd, connstring1);
            da1.Fill(ds);
            da1.Dispose();
            connstring1.Close();

da1.Fill(ds)之前的代码;正在工作并且安装了服务但是当 da1.Fill(ds);包含在代码中,服务不会启动。 我在 Web 应用程序中尝试了相同的代码,它工作正常。 这是我在 da1.Fill(ds) 时得到的;包括:

本地计算机上的 "ScheduledService" 服务已启动,然后 stopped.Some 服务在未被其他服务或程序使用时自动停止。

为了检查服务是否正常工作,我删除了上面的代码并将其替换为以下代码:

FileStream fs = new FileStream(@"d:\ScheduledService.txt",
FileMode.OpenOrCreate, FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(content);
//add the text to the underlying filestream
sw.Flush();
//close the writer
sw.Close();

服务很好。 我尝试搜索问题,但没有找到相关的解决方案。 请帮忙。提前致谢。

如果需要,请询问清楚。

编辑:对使用 DataReader 有什么想法吗?

因为da1.Fill(ds)是异常失败。检查事件日志是否有异常的任何详细信息。查看您的代码, 1)不需要像适配器那样为你打开和关闭连接, 2)处置方法应该在您关闭之后。 3) 为您的数据库对象使用 "using" 范围,它将隐式处理处理。

最后,不要在服务启动时这样做。服务启动实际上是为了任何初始化,应该 return 尽快。生成线程以执行任何其他活动。

您在评论中说您使用 Windows 身份验证,并且您的服务可能 运行ning 在本地系统帐户下。在您的windows帐户下使用SQL服务器身份验证或将服务设置为运行。

转到“服务”,然后是“服务”属性,然后在“登录”选项卡上选择您的 windows 用户: