C# UI线程/调度程序问题(BeginInvoke)

C# UI线程/调度程序问题(BeginInvoke),c#,C#,在前面的一个问题中,我问了如何在回调线程中访问UI元素。我得到了很多很好的答案,其中之一就是实现了这样一个包装器类: public static class UIThread { private static readonly Dispatcher Dispatcher; static UIThread() { Dispatcher = Deployment.Current.Dispatcher; } public static voi

在前面的一个问题中,我问了如何在回调线程中访问UI元素。我得到了很多很好的答案,其中之一就是实现了这样一个包装器类:

public static class UIThread
{
    private static readonly Dispatcher Dispatcher;

    static UIThread()
    {
        Dispatcher = Deployment.Current.Dispatcher;
    }

    public static void Invoke(Action action)
    {
        if (Dispatcher.CheckAccess())
        {
            action.Invoke();
        }
        else
        {
            Dispatcher.BeginInvoke(action);
        }
    }
}
你可以使用

UIThread.Invoke(() => TwitterPost.Text = "hello there");
但是,我尝试通过在回调函数中调用以下函数来扩展它

UIThread.Invoke(() => loadUserController(jsonObject));
使用以下方法:

private void loadUserController(JObject jsonObject)
{
    string profile_image_url = (string)jsonObject["profile_image_url"];
    string screen_name = (string)jsonObject["screen_name"];
    string name = (string)jsonObject["name"];
    string location = (string)jsonObject["location"];
    int statuses_count = (int)jsonObject["statuses_count"];

    if (!string.IsNullOrEmpty(profile_image_url))
    {
        ProfileImage.Source = new BitmapImage(new Uri("blahblahbalhb.jpg", UriKind.Absolute));
    }

    // Set the screen name and display name if it differs
    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(screen_name))
    {
        ScreenName.Text = screen_name;

        if (!screen_name.Equals(name))
        {
            _Name.Text = name;
        }
    }

    if (!string.IsNullOrEmpty(location))
    {
        Location.Text = location;
    }

    Tweets.Text = statuses_count.ToString() + " Tweets";
}
然后图像将不会呈现,直到另一个操作强制重画(单击按钮),但文本控件将更新。如果在我的回调函数中调用setImageFile(字符串imageFile),其实现方式如下:

private void setImageFile(string imageFile)
{
    if (this.Dispatcher.CheckAccess())
    {
        ProfileImage.Source = new BitmapImage(new Uri("fdsfdfdsf.jpg", UriKind.Absolute));
    }
    else
    {
        this.Dispatcher.BeginInvoke(new Action<string>(setImageFile), imageFile);
    }
}
private void setImageFile(字符串imageFile)
{
if(this.Dispatcher.CheckAccess())
{
ProfileImage.Source=新的位图图像(新的Uri(“fdsfdfdsf.jpg”,UriKind.Absolute));
}
其他的
{
this.Dispatcher.BeginInvoke(新操作(setImageFile)、imageFile);
}
}

然后图像将立即渲染。为什么会这样?我还不完全了解调度器的哪些属性?

我强烈建议您不要这样做
SynchronizationObject
设计用于处理此类场景,以及
AsyncOperation
AsyncOperationManager

SynchronizationObject
的唯一缺点是无法测试代码是否已经在正确的线程上运行。这不应该是一个问题,因为业务逻辑代码应该始终知道其线程上下文