c# - Windows 服务突然停止

标签 c# webclient

我有一个 Windows 服务应用程序,它向另一个网络服务发送一些消息(实习生作为电子邮件发送出去)并从服务器下载响应。

最近,服务每隔几天就会停止一次。 (尽管包含异常处理,但它仍未被捕获并且服务正在崩溃)。

事件查看器登录异常如下:

Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.Net.WebException Stack: at System.Net.ServicePointManager.FindServicePoint(System.Uri, System.Net.IWebProxy, System.Net.ProxyChain ByRef, System.Net.HttpAbortDelegate ByRef, Int32 ByRef) at System.Net.HttpWebRequest.FindServicePoint(Boolean) at System.Net.HttpWebRequest.get_ServicePoint() at System.Net.AuthenticationState.PrepareState(System.Net.HttpWebRequest) at System.Net.AuthenticationState.ClearSession(System.Net.HttpWebRequest) at System.Net.HttpWebRequest.ClearAuthenticatedConnectionResources()
at System.Net.HttpWebRequest.Abort(System.Exception, Int32) at System.Net.HttpWebRequest.AbortWrapper(System.Object) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

我搜索了很多,但找不到合适的答案。 任何帮助,将不胜感激。使用的代码:

public class DataAPIWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = 60000;
        return w;
    }
}

public string Send(string path)
{
    try
    {
        using (DataAPIWebClient webClient = new DataAPIWebClient())
        {
            webClient.Credentials = new NetworkCredential("XXX", "YYY");
            string reply = webClient.DownloadString(path);
            return reply;
        }
    }
    catch (WebException)
    {
        throw;
    }
}

最佳答案

这是你的问题

catch (WebException)
{
    throw;
}

你只是重新抛出你的异常,它永远不会被捕获,你永远不知道错误是什么,所以服务别无选择,只能崩溃

我可以建议

catch (WebException ex)
{
    Log.Error(ex);
    // Or write it to a file or something
}

Edit : As noted in the comments, this is not the solution as such, however you are missing the actual exception message in that stack trace due to the uncaught exception, however its the uncaught exception that is crashing your service

关于c# - Windows 服务突然停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47977673/

相关文章:

c# - VB.NET 到 C# - my.computer.getfiles()

c# - WebClient DownloadString 时底层连接被关闭异常

c# - Mono WebClient 编码问题

c# - 如何像在 C++ 中一样在 C# 中创建引用成员变量

c# - 编写 C++ .dll 并访问它们 Unity-3D

c# - 我应该为 ASP .NET MVC 应用程序使用内置的成员资格提供程序吗?

Java:HttpURLConnection 的 NIO 版本?

c# - 在 Windows 8 应用程序中使用 C# 从 NTP 服务器获取时间

c# - WebClient.UploadFileASync 的非常奇怪的行为

java - Web 客户端中的 ClassCastException