带有延迟的任务工厂方法

本文关键字:工厂 方法 任务 延迟 | 更新日期: 2023-09-27 18:07:33

我正在尝试调用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分钟延迟启动一个方法。

带有延迟的任务工厂方法

由于您不等待任务,也不等待(),因此从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
}

如果你的意思是有一个异常,你没有捕捉到它,那是因为你在没有等待结果的情况下开始了一个新任务。try-catch无法捕获异常,因为它存储在任务中,不会被重新抛出。

无论如何,如果你想要的是一个延迟使用Task.Delay与async-await而不是创建一个新的任务和阻塞它的线程:

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