Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It happens so because the lambda you pass to <code>Observable.Create</code> does not return the <code>CancellationDisposable</code> <strong>until</strong> it goes through all the steps. So, the order of actions is the following:</p> <ol> <li>You call <code>Subscribe</code></li> <li>UI thread blocks</li> <li>On a <code>ThreadPool</code> thread, the execution enters the lambda</li> <li><code>CancellationDisposable</code> is created</li> <li>You check for cancellation several times and execute the whole process. During this, your progress bar is updated.</li> <li><code>cancel</code> is returned from lambda</li> <li>UI thread is released and <code>obs</code> gets its value</li> <li>You click <code>Button2</code> and call <code>obs.Dispose</code></li> <li><code>cancel</code> gets <code>cancel.Token.IsCancellationRequested=true</code>. But nothing happens since everything has already happened.</li> </ol> <p>Here's the fixed code:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { var countObserver = Observable.Create&lt;int&gt;(observer =&gt; { var cancel = new CancellationDisposable(); // Here's the magic: schedule the job in background and return quickly var scheduledItem = Scheduler.ThreadPool.Schedule(() =&gt; { if (!cancel.Token.IsCancellationRequested) { //Step 1 of a long running process using lot of resources... observer.OnNext(1); } if (!cancel.Token.IsCancellationRequested) { //Step 2 of a long running process using lot of resources... observer.OnNext(1); } if (!cancel.Token.IsCancellationRequested) { //Step 3 of a long running process using lot of resources... observer.OnNext(1); } observer.OnCompleted(); }); return new CompositeDisposable(cancel, scheduledItem); }); obs = countObserver .ObserveOn(new ControlScheduler(this)) .Subscribe(i =&gt; { //Update a progress bar here... }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload