2010-08-16 89 views
0

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

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(string 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); 
    } 
} 

然后图像将立即呈现。这是为什么发生?调度员的哪些属性我不完全理解?

回答

0

我强烈建议你不是这样做。 SynchronizationObject旨在处理这种情况,以及AsyncOperationAsyncOperationManager

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