0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ObserveOnDispatcherの呼び出し場所に対する検証

Posted at

前の投稿で

var o = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(
    a => (obj, e) => a(e),
    h => this.watcher.Changed += h,
    h => this.watcher.Changed -= h,
    DispatcherScheduler.Current);
this.obs = o.ObserveOnDispatcher()
    .Select(x => GetContents(f))
    .Subscribe(x => {
        this.mainText.Text = x;
    });

と書いたけど、GetContents(f)がObserveOnDispatcher()の後だとUIスレッド上で処理することになる?
ということで次のようなコードを追加して検証してみる。

Console.WriteLine("1:" + Thread.CurrentThread.ManagedThreadId);
this.obs2 = o
    .Do(x => Console.WriteLine("2:" + Thread.CurrentThread.ManagedThreadId))
    .ObserveOnDispatcher()
    .Do(x => Console.WriteLine("3:" + Thread.CurrentThread.ManagedThreadId))
    .Subscribe(x => {
        Console.WriteLine("4:" + Thread.CurrentThread.ManagedThreadId);
    });

結果は次の通り。

1:10
-- (監視対象ファイルを変更する) --
2:11
2:6
3:10
4:10
3:10
4:10

やはりObservableOnDispatcher()の後だとUIスレッド上での処理になる。別にGetContentsをUIスレッドで処理しなければいけない理由はない(というよりUIスレッドでないほうが望ましい気が)ので次のように書くべきか。

var o = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(
    a => (obj, e) => a(e),
    h => this.watcher.Changed += h,
    h => this.watcher.Changed -= h,
    DispatcherScheduler.Current);
this.obs = o
    .Select(x => GetContents(f))
    .ObserveOnDispatcher()
    .Subscribe(x => {
        this.mainText.Text = x;
    });

ところで1回のファイル変更に対して2回イベントが呼ばれているけど、それは別途調査。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?