小编kri*_*ris的帖子

多线程环境中SendOrPostCallback和Action之间的区别?

我很擅长使用线程.我试图设定一个DependencyProperty值:

    public States State
    {
        get { return (States)GetValue(StateProperty); }
        set
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background,
                //(SendOrPostCallback)delegate { SetValue(StateProperty, value); }, //works
                (Action)(()=> SetValue(StateProperty, value)), //doesnt
                value);
        }
    }
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register("State", typeof(States), typeof(FTPDownload), new UIPropertyMetadata(States.Idle));
Run Code Online (Sandbox Code Playgroud)

我意识到在setter中你必须使用SendOrPostCallback(因为它在调用方法时提供了一个参数).它不适用于Action(因为缺少参数.而且,wpf真的是一个关于它的婊子,调试并找到TargetParameterCountException的原因,"没有源可用",根本没有线索.

为什么我必须在那里使用SendOrPostCallback?我怎么知道在这种情况下这是正确的?因为实际上通过以下方式调用setter:

Dispatcher.BeginInvoke((Action)(()=>State=States.Updating), null);
Run Code Online (Sandbox Code Playgroud)

并使用SendOrPostCallback而不是当然导致TargetParameterCountException ..

只是想知道看似不一致的事情是否只是常识?感觉有点迷失在这里,至少自从谷歌搜索SendOrPostCallback,Action和BeginInvoke作为关键字没有有意义的结果.

c# multithreading dependency-properties begininvoke

2
推荐指数
1
解决办法
6781
查看次数