Pergunta

I saw several posts with similar problem but no solution works :/

I debug a windows service by using a console application. It executes tasks on website and must be able to collect http code status for create logs. As you can see, sensitive code is in try/catch.

When I debug (F5), I have a WebException that is not caught. When I run (CTRL + F5), the exception's message is write in my console and stops my program. This is my code :

public partial class Schedulor : ServiceBase
{
void RunTasks()
    {
        schedulor.Start();
        List<Task> task = new List<Task>();
        foreach (TaskPlanner tp in listTp)
        {
            if (tp.CountDown == 0 && tp.IsRunning == false)
            {
                // Initialisation lors de GetTasks()
                tp.IsRunning = true;
                try
                {
                    task.Add(Task.Factory.StartNew(() => tr = tp.ExecuteBot.Execute())); // WEBEXECPTION HERE (cannot find 404)
                }
                catch (Exception e)
                {                        
                    if (e is WebException)
                    {
                        // treatment
                    }                       
                }                    
            }
        }
        Task.WaitAll(task.ToArray());
        CreateLogs();
    }
  }


 public class Bot : IBot
 {
 public TaskResult Execute()
    {
        TaskResult tr = new TaskResult();
        int codeResponse, timeout;
        string credentials;
        try
        {
            WebRequest wrSettings = WebRequest.Create(settings.Url);

            // treatment
        }
        catch (Exception e)
        {
            //Console.WriteLine(e.Message);                
            if (e is WebException)
            {
                var code = ((HttpWebResponse)((WebException)e).Response).StatusCode;
                if ((int)code != settings.HttpResponse)
                {
                    tr.MyResult = TaskResult.Result.nok;
                    goto next;
                }
                else tr.MyResult = TaskResult.Result.ok;
            }
        }            
    next:
        return tr;
    }
 }

I do not understand why my catch does not work. I need to treat this information because the task can test if a website return 404 or anything else.

Thanks in advance

EDIT : -----------

I reduce code as it requests because deleted code does not the real problem

Foi útil?

Solução

You should catch that exception in task. Add another method, and create your tasks similar to:

task.Add(Task.Factory.StartNew(() =>  Process(tp)));

void Process(TaskPlanner tp)
{
    try
    {
        tp.ExecuteBot.Execute();
    }
    catch (WebException wex)
    {
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top