如果超过5分钟,则终止Web Service中的功能

时间:2019-01-15 09:33:37

标签: c# multithreading web-services

如果功能在5分钟内未完成,如何终止功能并在Web服务中返回响应?

我不知道如何执行此操作。.我看到了一些使用线程的示例,因此到目前为止,我一直在尝试以下操作:

public void myfunction(){
    Thread workerThread = Thread.CurrentThread;
    bool finished = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(30000), () =>
    {
       .....long time execution here....

    });

    if (!finished)
    {
        workerThread.Abort();
    }
}


public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
    {
        try
        {
            Thread workerThread = new Thread(() => codeBlock());
            workerThread.Start();

            bool finished = workerThread.Join(timeSpan);


            return finished;

        }
        catch (AggregateException ae)
        {
            throw ae.InnerExceptions[0];
        }
    }

0 个答案:

没有答案