Dispatcher BeginInvoke Syntax

后端 未结 3 1648
灰色年华
灰色年华 2020-12-04 16:23

I have been trying to follow some WCF Data Services examples and have the following code:

private void OnSaveCompleted(IAsyncResult result)
    {
        Disp         


        
相关标签:
3条回答
  • 2020-12-04 17:00

    If your method does not require parameters, this is the shortest version I've found

    Application.Current.Dispatcher.BeginInvoke((Action)MethodName); 
    
    0 讨论(0)
  • 2020-12-04 17:06

    Answer by Jon Skeet is very good but there are other possibilities. I prefer "begin invoke new action" which is easy to read and to remember for me.

    private void OnSaveCompleted(IAsyncResult result)
    {       
        Dispatcher.BeginInvoke(new Action(() =>
        {
            context.EndSaveChanges(result);
        }));
    }
    

    or

    private void OnSaveCompleted(IAsyncResult result)
    {       
        Dispatcher.BeginInvoke(new Action(delegate
        {
            context.EndSaveChanges(result);
        }));
    }
    

    or

    private void OnSaveCompleted(IAsyncResult result)
    {       
        Dispatcher.BeginInvoke(new Action(() => context.EndSaveChanges(result)));
    }
    
    0 讨论(0)
  • 2020-12-04 17:14

    The problem is that the compiler doesn't know what kind of delegate you're trying to convert the lambda expression to. You can fix that either with a cast, or a separate variable:

    private void OnSaveCompleted(IAsyncResult result)
    {        
        Dispatcher.BeginInvoke((Action) (() =>
        {
            context.EndSaveChanges(result);
        }));
    }
    

    or

    private void OnSaveCompleted(IAsyncResult result)
    {
        Action action = () =>
        {
            context.EndSaveChanges(result);
        };
        Dispatcher.BeginInvoke(action);
    }
    
    0 讨论(0)
提交回复
热议问题