带延迟的任务工厂方法

Task Factory Method with Delay

我正在尝试调用延迟 5 分钟的特定方法:

try
{
    HttpContext ctx = HttpContext.Current;
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
       HttpContext.Current = ctx;
       System.Threading.Thread.Sleep(5 * 60 * 1000);
       Sendafter5mins(param1,params2);
    });
}
catch (Exception EX)
{
    //Log Exception if any  
}

此方法有时无提示地失败,日志中没有任何异常。

请告诉我这是延迟 5 分钟触发方法的正确方法吗?

如果 "failing silently" 你的意思是有一个异常但你没有捕捉到它,那是因为你没有等待结果就开始了一个新任务。您的 try-catch 无法捕获异常,因为它存储在任务中并且不会重新抛出。

无论如何,如果您想要的只是延迟,请使用 Task.Delay 和 async-await 而不是创建新任务并阻塞其线程:

async Task SendAfterDelay()
{
    try
    {
        await Task.Delay(TimeSpan.FromMinutes(5));
        Sendafter5mins(param1,params2);
    }
    catch (Exception e)
    {
        // handle exception
    }
}    

由于您不等待任务,也不在其上等待 (),因此从 Sendafter5mins(..) 抛出的任何异常将 不会 被捕获到您的 catch 堵塞。如果您不使用 .NET 4.5,则整个过程应该会失败,因为异常会使终结器线程失败。将您的代码更改为:

try
{
    HttpContext ctx = HttpContext.Current;
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        try
        {
            HttpContext.Current = ctx;
            System.Threading.Thread.Sleep(5 * 60 * 1000);
            Sendafter5mins(param1,params2);
        }
        catch(Exception e)
        {
            //Log Exception if any
        }

    });
}
catch (Exception EX)
{
    //This will catch unlikely exceptions thrown from HttpContext ctx = HttpContext.Current 
    //  or the creation of the Task
}