C#의 Console 에서 Ctrl+C (Cancel) 처리

2023. 5. 16. 14:53· C#
목차
  1. ✅ Console Application - Cancel (Ctrl+C)
  2. ConsoleCancelEventHandler
  3. 람다 & delegate
  4. ✅ Console Application - Cancel (Ctrl+C) 끝

C#의 Console Application에서 Ctrl+C 를 입력했을 때 특별한 이벤트를 발생시키는 방법입니다. Console에서 구동 중인 Application을 중단할 때 종료 이벤트를 수행하는 것으로 로그 수집 종료, 메모리 반환 등의 코드가 수행되도록 처리하는 것이 일반적입니다.

 

 


 

 

 

✅ Console Application - Cancel (Ctrl+C)

 

 

 

ConsoleCancelEventHandler

 

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);

        // Ctrl+C 가 발생할 때 까지 무한루프
        while (true) { }
    }

    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        // 즉시 종료되는 것을 방지함
        e.Cancel = true;

        Console.WriteLine("Ctrl+C pressed");
    }
}

 

 

 


 

 

람다 & delegate

 

람다, delegate를 사용하여 코드를 줄이고 전역 bool 을 사용하여 Ctrl+C 가 발생했을 때 무한루프를 종료하는 코드입니다.

https://stackoverflow.com/questions/177856/how-do-i-trap-ctrlc-sigint-in-a-c-sharp-console-app

 

How do I trap Ctrl+C (SIGINT) in a C# console app?

I would like to be able to trap Ctrl+C in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?

stackoverflow.com

 

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object? sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };
        
        while (MainClass.keepRunning) {
            // Do your work in here, in small chunks.
            // If you literally just want to wait until Ctrl+C,
            // not doing anything, see the answer using set-reset events.
        }
        Console.WriteLine("exited gracefully");
    }
}

 

위 코드는 stackoverflow.com 에서 발췌했습니다.

 

 

 

 

 

✅ Console Application - Cancel (Ctrl+C) 끝

  1. ✅ Console Application - Cancel (Ctrl+C)
  2. ConsoleCancelEventHandler
  3. 람다 & delegate
  4. ✅ Console Application - Cancel (Ctrl+C) 끝
'C#' 카테고리의 다른 글
  • C# 에서 설정 저장하는 'ini' 간편 소스코드
  • C# : ICloneable 사용법
  • C# : 어트리뷰트 (Attribute)는 뭘까요?
  • 자료구조: 다중 트리 (Multi-Tree)
YUNYUN3915
YUNYUN3915

공지사항

  • 블로그 이전 취소

인기 글

태그

  • WindowsFormsHostingWpfControl
  • wpf 전역 스타일
  • wpf
  • ICloneable
  • command
  • DataGrid
  • Expanding Event
  • IDialogService
  • Git취소
  • CS8602
  • TreeView
  • 메세지팝업
  • DialogService
  • PasswordBox MVVM
  • RelayCommand
  • WPF 흰색바
  • GIT
  • IValueConverter
  • 윈도우탐색기
  • C#
  • WPF style
  • ElementHost
  • PasswordBox DataBinding
  • 어트리뷰트
  • TreeViewItem
  • 문자열 관리
  • ItemsControl
  • itemssource
  • wpf 폰트
  • OnPropertyChanged
hELLO · Designed By 정상우.v4.2.0
YUNYUN3915
C#의 Console 에서 Ctrl+C (Cancel) 처리
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.