programing

InvokeAsync와 Begin의 차이점은 무엇입니까?WPF 디스패처 호출

css3 2023. 4. 10. 22:06

InvokeAsync와 Begin의 차이점은 무엇입니까?WPF 디스패처 호출

에 주목했습니다.WPF 디스패처는 InvokeAsync라고 불리는 디스패처의 스레드 상의 내용을 실행하기 위한 새로운 메서드 세트를 취득했습니다.전에.NET 4.5 호출시작 각각 동기 및 비동기적으로 처리한 호출.

네이밍과 사용 가능한 오버로드가 약간 다른 것 외에, 이 두 가지 사이에 큰 차이가 있습니까?BeginInvoke및 그InvokeAsync방법?

아, 그리고 내가 이미 확인했는데 둘 다 그럴 수 있어awaited:

private async Task RunStuffOnUiThread(Action action)
{
    // both of these works fine
    await dispatcher.BeginInvoke(action);
    await dispatcher.InvokeAsync(action);
}

예외 처리는 다릅니다.

다음 사항을 체크할 수 있습니다.

private async void OnClick(object sender, RoutedEventArgs e)
{
    Dispatcher.UnhandledException += OnUnhandledException;
    try
    {
        await Dispatcher.BeginInvoke((Action)(Throw));
    }
    catch
    {
        // The exception is not handled here but in the unhandled exception handler.
        MessageBox.Show("Catched BeginInvoke.");
    }

    try
    {
       await Dispatcher.InvokeAsync((Action)Throw);
    }
    catch
    {
        MessageBox.Show("Catched InvokeAsync.");
    }
}

private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    MessageBox.Show("Catched UnhandledException");
}

private void Throw()
{
    throw new Exception();
}

다른 점은 없습니다.BeginInvoke메서드는 프라이빗을 호출합니다.LegacyBeginInvokeImplislef가 프라이빗 메서드라고 부르는 메서드InvokeAsyncImpl(에 의해 사용되는 방법)InvokeAsync)는 기본적으로 같은 것입니다.간단한 리팩터링인 것 같은데 이상하게도BeginInvoke메서드는 사용되지 않습니다.

BeginInvoke:

public DispatcherOperation BeginInvoke(DispatcherPriority priority, Delegate method)
{
    return this.LegacyBeginInvokeImpl(priority, method, null, 0);
}

private DispatcherOperation LegacyBeginInvokeImpl(DispatcherPriority priority, Delegate method, object args, int numArgs)
{
    Dispatcher.ValidatePriority(priority, "priority");
    if (method == null)
    {
        throw new ArgumentNullException("method");
    }
    DispatcherOperation dispatcherOperation = new DispatcherOperation(this, method, priority, args, numArgs);
    this.InvokeAsyncImpl(dispatcherOperation, CancellationToken.None);
    return dispatcherOperation;
}

InvokeAsync:

public DispatcherOperation InvokeAsync(Action callback, DispatcherPriority priority)
{
    return this.InvokeAsync(callback, priority, CancellationToken.None);
}

public DispatcherOperation InvokeAsync(Action callback, DispatcherPriority priority, CancellationToken cancellationToken)
{
    if (callback == null)
    {
        throw new ArgumentNullException("callback");
    }
    Dispatcher.ValidatePriority(priority, "priority");
    DispatcherOperation dispatcherOperation = new DispatcherOperation(this, priority, callback);
    this.InvokeAsyncImpl(dispatcherOperation, cancellationToken);
    return dispatcherOperation;
}

메서드 시그니처에는 다음 차이가 있습니다.

BeginInvoke(Delegate, Object[])
InvokeAsync(Action)

위해서BeginInvoke()컴파일러가 어레이를 만듭니다.Object[]을 위해 암묵적으로InvokeAsync()이러한 배열은 필요하지 않습니다.

IL_0001:  ldarg.0
IL_0002:  call       instance class [WindowsBase]System.Windows.Threading.Dispatcher [WindowsBase]System.Windows.Threading.DispatcherObject::get_Dispatcher()
IL_0007:  ldarg.1
IL_0008:  ldc.i4.0
IL_0009:  newarr     [mscorlib]System.Object
IL_000e:  callvirt   instance class [WindowsBase]System.Windows.Threading.DispatcherOperation [WindowsBase]System.Windows.Threading.Dispatcher::BeginInvoke(class [mscorlib]System.Delegate, object[])


IL_0014:  ldarg.0
IL_0015:  call       instance class [WindowsBase]System.Windows.Threading.Dispatcher [WindowsBase]System.Windows.Threading.DispatcherObject::get_Dispatcher()
IL_001a:  ldarg.1
IL_001b:  callvirt   instance class [WindowsBase]System.Windows.Threading.DispatcherOperation [WindowsBase]System.Windows.Threading.Dispatcher::InvokeAsync(class [mscorlib]System.Action)

음, 한 가지 차이점은 InvokeAsync는 DispatcherOperation을 반환값으로 반환하고 Func를 위임 입력 파라미터로 받아들이는 일반적인 오버로드가 있다는 것입니다.따라서 InvokeAsync를 통해 작업 결과를 가져올 수 있습니다.이는 작업 결과를 기다리는 방법과 유사한 유형 안전 방법입니다.

언급URL : https://stackoverflow.com/questions/13412670/whats-the-difference-between-invokeasync-and-begininvoke-for-wpf-dispatcher