오보에블로그

[c#] TimeOutException이 catch되지 않을때 본문

C++ & C#/C#

[c#] TimeOutException이 catch되지 않을때

(OBO) 2019. 8. 4. 14:32
728x90

try , catch 구문에서

try에 다른 프로그램을 실행시킬때,

error를 catch 하지 못할때가 있습니다.

(설령 catch 한다고 하더라도 프로그램이 끝난후에야 catch 될 때)

 

그럴 때는 비동기 thread인 task를 이용하고

아주 멋지신 분이 정리 해놓은 코드를 사용하도록 합시다.

 https://pastebin.com/K8MWQuJ6

 

[C#] Task with timeout - Pastebin.com

Not a member of Pastebin yet? Sign Up, it unlocks many cool features! class Program     {         static void Main(string[] args)         {             var program = new Program();             program.Test().Wait();             Console.WriteLine("Press ent

pastebin.com

 

 

class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.Test().Wait();
 
            Console.WriteLine("Press enter to quit.");
            Console.ReadLine();
        }
 
        public async Task Test()
        {
            await DoWithTimeout(() =>
            {
                Console.WriteLine("Starting main action...");
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(7));
                Console.WriteLine("Finishing main action");
            },
            () => Console.WriteLine("Timeout action is invoked"),
            TimeSpan.FromSeconds(5));
        }
 
        public async Task DoWithTimeout(Action action, Action timeoutAction, TimeSpan timeout)
        {
            var cancellatinSource = new CancellationTokenSource();
 
            var task = Task.Run(action, cancellatinSource.Token);
 
            if (await Task.WhenAny(task, Task.Delay(timeout)) != task)
            {
                cancellatinSource.Cancel();
                timeoutAction();
            }
        }
    }
728x90

'C++ & C# > C#' 카테고리의 다른 글

[C#API] Comparison<T>  (0) 2021.12.30
[C#API] 알아두면 유용한 IEnumerable 관련 메소드  (0) 2021.12.16
[C#API] IEnumerator & IEnumerable  (0) 2021.12.16
[C# API] String Builder  (0) 2021.10.21
[c#] Longest Common Substring  (0) 2019.08.04