2011-12-13 53 views
0

對不起,我還是不明白,UI是如何工作的,什麼是Dispatcher調度WCF模型 - 添加方法

我有這樣DispatchingWcfModel

public interface IWcfModel 
{ 
    List<ConsoleData> DataList { get; set; } 
    event Action<List<ConsoleData>> DataArrived; 
} 

class DispatchingWcfModel : IWcfModel 
{ 

    private readonly IWcfModel _underlying; 
    private readonly Dispatcher _currentDispatcher; 

    public DispatchingWcfModel(IWcfModel model) 
    { 
     _currentDispatcher = Dispatcher.CurrentDispatcher; 
     _underlying = model; 
     _underlying.DataArrived += _underlying_DataArrived; 
    } 

    private void _underlying_DataArrived(List<ConsoleData> obj) 
    { 
     Action dispatchAction =() => 
     { 
      if (DataArrived != null) 
      { 
       DataArrived(obj); 
      } 
     }; 
     _currentDispatcher.BeginInvoke(DispatcherPriority.DataBind, dispatchAction); 
    } 

    public List<ConsoleData> DataList 
    { 
     get { throw new NotImplementedException(); } 
     set { throw new NotImplementedException(); } 
    } 

    public event Action<List<ConsoleData>> DataArrived; 
} 

現在我想補充int[] ConnectionStats { get; set; }。我應該爲它引入單獨的事件嗎?我應該在DispatchingWcfModel中編寫什麼?我想有接口這樣的:

public interface IWcfModel 
{ 
    List<ConsoleData> DataList { get; set; } 
    int[] ConnectionStats { get; set; } 
    event Action<List<ConsoleData>> DataArrived; 
} 
+2

如果你不明白你在做什麼,你爲什麼要修改它? – x0n

+0

我希望我能夠理解使用這些例子:) – javapowered

+0

你讀過[參考](http://msdn.microsoft.com/en-us/library/ms741870.aspx)? –

回答

0

Dispatcher是WPF的主UI線程內部消息隊列。它可以用於其他線程在應用程序的主UI線程上運行命令。

這很重要,因爲WPF不允許您訪問在其他線程上創建的對象。例如,如果在主UI線程上創建了Button,則不能從另一個線程修改該按鈕,但可以使用另一個線程的Dispatcher向主UI線程發送命令來更新該按鈕。

這適用於所有對象,而不僅僅是UI元素。如果在一個線程上創建了類似ObservableCollection的內容,則另一個線程無法修改它。正因爲如此,所有對象通常都是在主UI線程上創建的。

調度程序消息可以同步或異步處理,它們可以具有不同的優先級。在您的代碼中,您使用的是_currentDispatcher.BeginInvoke(DispatcherPriority.DataBind, dispatchAction);,這意味着它將開始與主UI線程的異步操作,並以與DataBinding相同的優先級運行它。您可以在DispatcherPrioritieshere上查看更多信息。

如果您的ConnectionStats集合異步獲取其數據,那麼您將需要添加某種DataArrived方法,該方法將從非UI線程獲取數據並將其添加到集合中。如果數據是獲取並打包在一起,則可以使用現有的DataArrived方法,或者如果數據是單獨獲取的,則可以創建自己的數據。如果它同步獲取數據,則不需要做任何特別的事情。

從外觀看,_underlying_DataArrived是爲了在後臺線程上運行(意思是它不能改變你的集合,它應該在主UI線程上創建),而DataArrived是爲了在主UI上運行線。