6 Haziran 2016 Pazartesi

WPF Dispatcher

Giriş
Dispatcher nesnesine şöyle erişiriz.
Application.Current.Dispatcher.XXX ();
Thread içinden şöyle erişiriz.
Dispatcher.CurrentDispatcher.XXX ();
BeginInvoke metodu
Şöyle yaparız.
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
  ...
}));
Invoke metodu
Şöyle yaparız.
Dispatcher.Invoke(() => ...);
Başka thread içinden ekran açmak için şöyle yaparız.
public Task<string> GetLoginCode()
{
  return Task.Run(() =>
  {
    CodeRequestViewModel viewModel = new CodeRequestViewModel();
    Application.Current.Dispatcher.Invoke(delegate 
    {
      CodeRequestView view = new CodeRequestView();
      view.ShowDialog();
    });
    return viewModel.Code;
  });
}
Run metodu
Bir console uygulamasında Dispatcher şöyle çalıştırılır.
class Program
{
  static void Main(string[] args)
  {
    var thread = new Thread(() =>
    {
      Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
      {
        Console.WriteLine("Hello world from Dispatcher");
      }));

      Dispatcher.Run();
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
  }
}


Hiç yorum yok:

Yorum Gönder