Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우

WPF 프로젝트를 만들고, 다음과 같이 BeginInvoke를 호출하려고 했습니다.

using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 컴파일 오류 발생: CS1660
            this.Dispatcher.BeginInvoke((arg) =>
            {

            }, null);
        }
    }
}

그런데, 다음과 같은 컴파일 오류가 발생합니다.

error CS1660: Cannot convert lambda expression to type 'DispatcherPriority' because it is not a delegate type

// 또는

error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

정말 이상하군요... 예전에 잘 사용한 적이 있었던 것 같은데?!!!

이런 경우, 다음과 같이 바꿔주면 컴파일이 잘 됩니다.

// 전달해야 할 인자가 있는 경우,
this.Dispatcher.BeginInvoke((System.Action<object>)((arg) =>
{
    MessageBox.Show("TEST");
}), this);


// 전달해야 할 인자가 없는 경우,
this.Dispatcher.BeginInvoke((System.Action)(() =>
{
    MessageBox.Show("TEST");
}), null);

그래도 왠지... 명시적인 형 변환이 마음에 들지 않습니다. 그래서 검색해 봤는데 뜻밖의 글이 나오는군요. ^^

Dispatcher.BeginInvoke: Cannot convert lambda to System.Delegate
; http://stackoverflow.com/questions/4936459/dispatcher-begininvoke-cannot-convert-lambda-to-system-delegate

그러니까, "System.Windows.Presentation" 어셈블리를 참조한 후, "using System.Windows.Threading;" 선언을 추가하면 BeginInvoke에 Action을 받도록 하는 확장 메서드가 포함되기 때문에,

namespace System.Windows.Threading
{
    public static class DispatcherExtensions
    {
        public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action);
        public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority);
        public static void Invoke(this Dispatcher dispatcher, Action action);
        public static void Invoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority);
        public static void Invoke(this Dispatcher dispatcher, Action action, TimeSpan timeout);
        public static void Invoke(this Dispatcher dispatcher, Action action, TimeSpan timeout, DispatcherPriority priority);
    }
}

이렇게 호출하는 코드가 정상적으로 컴파일이 됩니다.

this.Dispatcher.BeginInvoke(() =>
{
    MessageBox.Show("TEST");
});

하지만, 보는 바와 같이 Action에 인자 전달을 받는 것은 확장 메서드로 재정의되어 있지 않기 때문에 다음과 같은 코드의 경우 여전히 오류가 발생합니다.

// error CS1660: Cannot convert lambda expression to type 'DispatcherPriority' because it is not a delegate type
this.Dispatcher.BeginInvoke((arg) =>
{
    MessageBox.Show("TEST");
}, this);

위와 같이 인자를 전달하려면 어쩔 수 없이 명시적인 Action 형 변환을 해야만 합니다.

using System.Windows;
using System.Windows.Threading;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Dispatcher.BeginInvoke((System.Action<object>)((arg) =>
            {
                MessageBox.Show("TEST");
            }), this);

            // 또는,

            this.Dispatcher.BeginInvoke((System.Action<MainWindow>)((arg) =>
            {
                MessageBox.Show("TEST");
            }), this);
        }
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/27/2017]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11734정성태10/10/201811966Linux: 4. Synology NAS(DS216+II)에 FTDI 장치 연결 후 C#(.NET Core)으로 DTR 제어파일 다운로드1
11733정성태10/10/201813853Linux: 3. Synology NAS(DS216+II)에서 FTDI 장치를 C/C++로 제어
11732정성태10/10/201813905디버깅 기술: 119. windbg 분석 사례 - 종료자(Finalizer)에서 예외가 발생한 경우 비정상 종료(Crash) 발생파일 다운로드1
11731정성태10/9/201813139개발 환경 구성: 409. C# - REST API를 이용해 Azure Kudu 서비스 이용 - 웹 앱 확장 처리파일 다운로드1
11730정성태10/9/201812200개발 환경 구성: 408. C# - REST API를 이용해 Azure Kudu 서비스 이용 - 파일 처리파일 다운로드1
11729정성태10/9/201814288Windows: 150. 윈도우에서 ARP Cache 목록 확인 및 삭제하는 방법
11728정성태10/9/201813051사물인터넷: 50. Audio Jack 커넥터의 IR 적외선 송신기 [1]
11727정성태10/8/201813792오류 유형: 491. Visual Studio의 리눅스 SSH 원격 연결 - "Connectivity Failure. Please make sure host name and port number are correct."
11726정성태10/7/201816028사물인터넷: 49. 라즈베리 파이를 이용해 원격 컴퓨터의 전원 스위치 제어파일 다운로드1
11724정성태10/5/201814739개발 환경 구성: 407. 유니코드와 한글 - "Hangul Compatibility Jamo"파일 다운로드1
11723정성태10/4/201811376개발 환경 구성: 406. "Docker for Windows" 컨테이너 내의 .NET Core 응용 프로그램에서 직렬 포트(Serial Port, COM Port) 사용 방법
11722정성태10/4/201813203.NET Framework: 798. C# - Hyper-V 가상 머신의 직렬 포트와 연결된 Named Pipe 간의 통신파일 다운로드1
11721정성태10/4/201813962.NET Framework: 797. Linux 환경의 .NET Core 응용 프로그램에서 직렬 포트(Serial Port, COM Port) 사용 방법파일 다운로드1
11720정성태10/4/201815093개발 환경 구성: 405. Hyper-V 가상 머신에서 직렬 포트(Serial Port, COM Port) 사용
11719정성태10/4/201816162.NET Framework: 796. C# - 인증서를 윈도우에 설치하는 방법
11718정성태10/4/201811431개발 환경 구성: 404. (opkg가 설치된) Synology NAS(DS216+II)에 cmake 설치
11717정성태10/3/201813560사물인터넷: 48. 넷두이노의 C# 네트워크 프로그램 [1]
11716정성태10/3/201814363사물인터넷: 47. Raspberry PI Zero (W)에 FTDI 장치 연결 후 C/C++로 DTR 제어파일 다운로드1
11715정성태10/3/201813944사물인터넷: 46. Raspberry PI Zero (W)에 docker 설치
11714정성태10/2/201812707사물인터넷: 45. Raspberry PI에 ping을 hostname으로 하는 방법
11713정성태10/2/201815392개발 환경 구성: 403. Synology NAS(DS216+II)에 docker 설치 후 .NET Core 2.1 응용 프로그램 실행하는 방법
11712정성태10/2/201819886.NET Framework: 795. C# - 폰트 목록을 한글이 아닌 영문으로 구하는 방법 [3]
11711정성태10/2/201815679오류 유형: 490. 윈도우 라이선스 키 입력 오류 0xc004f050, 0xc004e028
11710정성태10/2/201814101.NET Framework: 794. C# - 같은 모양, 다른 값의 한글 자음을 비교하는 호환 분해 [5]
11709정성태9/30/201812336개발 환경 구성: 402. .NET Core 콘솔 응용 프로그램을 docker로 실행/디버깅하는 방법 [1]
11708정성태9/30/201814561개발 환경 구성: 401. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 [2]파일 다운로드1
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...