how do set a timeout for a method

前端 未结 8 1330
情书的邮戳
情书的邮戳 2020-12-25 15:10

how do set a timeout for a busy method +C#.

8条回答
  •  盖世英雄少女心
    2020-12-25 15:48

    This is an old question but it has a simpler solution now that was not available then: Tasks!

    Here is a sample code:

    var task = Task.Run(() => LongRunningMethod());//you can pass parameters to the method as well
    if (task.Wait(TimeSpan.FromSeconds(30)))
        return task.Result; //the method returns elegantly
    else
        throw new TimeoutException();//the method timed-out
    

提交回复
热议问题