开发者

HttpWebRequest timeout in Windows service

I am getting a timeout error while starting my Windows service. I am tring to download an XML 开发者_运维百科file from a remote system which causes a timeout during the service OnStart.

This is the method I am calling from OnStart:

public static StreamReader GetResponseStream()
{
    try
    {
        EventLog.WriteEntry("Epo-Service_Retriver", "Trying ...",
            EventLogEntryType.Information);

        CookieContainer CC = new CookieContainer();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
            Utils.GetWeeklyPublishedURL());
        request.Proxy = null;
        request.UseDefaultCredentials = true;
        request.KeepAlive = true; //THIS DOES THE TRICK
        request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
        request.CookieContainer = CC;

        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());

        EventLog.WriteEntry("Epo-Service_Retriver", "Connected to Internet...",
            EventLogEntryType.SuccessAudit);
        return reader;
    }
}

Is there any possibility to avoid this timeout?


You'll want to start a thread to do that work.

This is how I recall doing it in 1.1 (this is little more than pseudo code), something like this;

protected override void OnStart(string[] args)
{
    Foo f = new Foo(args);
    f.MethodThatNeverExits();
}

private void MethodThatNeverExits()
{
    LongRunningInitialization();
    while (true)
    {
        Thread.Sleep(pollingInterval);
        DoSomeWork();
    }
}

Would become;

private AutoResetEvent shutDownEvent;
private Thread thread;

protected override void OnStart(string[] args)
{
    shutDownEvent = new AutoResetEvent(false);

    Foo f = new Foo(args);
    thread = new Thread(new ThreadStart(f.MethodThatNeverExits()));
    thread.Start();         
}

private void MethodThatNeverExits()
{
    LongRunningInitialization();
    while (!shutDownEvent.WaitOne(pollingInterval, false))
    {
        DoSomeWork();
    }
}

protected override void OnStop()
{
    shutDownEvent.Set();
    thread.Join(timeToWait);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜