Saturday, February 5, 2011

ObservableDictionary do DR WPF com dispatcher

Eu uso o ObservableDictionary que DR WPF forneceu para WPF , porem tive problemas quando mudei o dicionario em thread diferente do que o thread que o dicionario foi criado – os eventos: CollectionChanged / PropertyChanged executaram em thread diferente. (gente como falo "thread" em portugues, mas na nossa lingua de programadores ??? סמיילי )

Entao eu mudei o codigo um pouco para suportar isso. As mudanças sao:

1. Nos constructors adicionei parâmetros opcionais para o dispatcher & DispatcherPriority (padrao para DispatcherPriority.DataBind).

public ObservableDictionary(Dispatcher dispatcher = null,DispatcherPriority dispatcherPriority = DispatcherPriority.DataBind)

{

    _dispatcher = dispatcher;

    _dispatcherPriority = dispatcherPriority;

    _keyedEntryCollection = new KeyedDictionaryEntryCollection<TKey>();

}

2. Nos methodos que executa os OnCollectionChanged and OnPropertyChanged eventos verifiquei se o dispatcher nao e null – e ai executei o evento com o dispatcher no lugar de executar ele no thread que chamou ele.

protected
virtual
void OnCollectionChanged(NotifyCollectionChangedEventArgs args)

{

    var handler = CollectionChanged;

    if (handler != null)

    {

    if (_dispatcher != null)

    {

        if (_dispatcher.CheckAccess())

        {

            handler(this, args);

        }

        else

        {

            _dispatcher.Invoke((Action)(() => handler(this, args)), _dispatcherPriority);

        }

    }

    else

    {

        handler(this, args);

    }

    }

}

O codigo completo esta aqui.

 

No comments:

Post a Comment