Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Windows.Threading/Reactive/Concurrency/CoreDispatcherScheduler.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 #if WINDOWS
4 using System.Reactive.Concurrency;
5 using System.Reactive.Disposables;
6 using System.Runtime.ExceptionServices;
7 using System.Threading;
8 using Windows.UI.Core;
9 using Windows.UI.Xaml;
10
11 namespace System.Reactive.Concurrency
12 {
13 /// <summary>
14 /// Represents an object that schedules units of work on a Windows.UI.Core.CoreDispatcher.
15 /// </summary>
16 /// <remarks>
17 /// This scheduler type is typically used indirectly through the <see cref="System.Reactive.Linq.DispatcherObservable.ObserveOnDispatcher&lt;TSource&gt;(IObservable&lt;TSource&gt;)"/> and <see cref="System.Reactive.Linq.DispatcherObservable.SubscribeOnDispatcher&lt;TSource&gt;(IObservable&lt;TSource&gt;)"/> methods that use the current Dispatcher.
18 /// </remarks>
19 public sealed class CoreDispatcherScheduler : LocalScheduler, ISchedulerPeriodic
20 {
21 private readonly CoreDispatcher _dispatcher;
22 private readonly CoreDispatcherPriority _priority;
23
24 /// <summary>
25 /// Constructs a CoreDispatcherScheduler that schedules units of work on the given Windows.UI.Core.CoreDispatcher.
26 /// </summary>
27 /// <param name="dispatcher">Dispatcher to schedule work on.</param>
28 /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
29 public CoreDispatcherScheduler(CoreDispatcher dispatcher)
30 {
31 if (dispatcher == null)
32 throw new ArgumentNullException("dispatcher");
33
34 _dispatcher = dispatcher;
35 _priority = CoreDispatcherPriority.Normal;
36 }
37
38 /// <summary>
39 /// Constructs a CoreDispatcherScheduler that schedules units of work on the given Windows.UI.Core.CoreDispatcher with the given priority.
40 /// </summary>
41 /// <param name="dispatcher">Dispatcher to schedule work on.</param>
42 /// <param name="priority">Priority for scheduled units of work.</param>
43 /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is null.</exception>
44 public CoreDispatcherScheduler(CoreDispatcher dispatcher, CoreDispatcherPriority priority)
45 {
46 if (dispatcher == null)
47 throw new ArgumentNullException("dispatcher");
48
49 _dispatcher = dispatcher;
50 _priority = priority;
51 }
52
53 /// <summary>
54 /// Gets the scheduler that schedules work on the Windows.UI.Core.CoreDispatcher associated with the current Window.
55 /// </summary>
56 public static CoreDispatcherScheduler Current
57 {
58 get
59 {
60 var window = Window.Current;
61 if (window == null)
62 throw new InvalidOperationException(Strings_WindowsThreading.NO_WINDOW_CURRENT);
63
64 return new CoreDispatcherScheduler(window.Dispatcher);
65 }
66 }
67
68 /// <summary>
69 /// Gets the Windows.UI.Core.CoreDispatcher associated with the CoreDispatcherScheduler.
70 /// </summary>
71 public CoreDispatcher Dispatcher
72 {
73 get { return _dispatcher; }
74 }
75
76 /// <summary>
77 /// Gets the priority at which work is scheduled.
78 /// </summary>
79 public CoreDispatcherPriority Priority
80 {
81 get { return _priority; }
82 }
83
84 /// <summary>
85 /// Schedules an action to be executed on the dispatcher.
86 /// </summary>
87 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
88 /// <param name="state">State passed to the action to be executed.</param>
89 /// <param name="action">Action to be executed.</param>
90 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
91 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
92 public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
93 {
94 if (action == null)
95 throw new ArgumentNullException("action");
96
97 var d = new SingleAssignmentDisposable();
98
99 var res = _dispatcher.RunAsync(_priority, () =>
100 {
101 if (!d.IsDisposed)
102 {
103 try
104 {
105 d.Disposable = action(this, state);
106 }
107 catch (Exception ex)
108 {
109 //
110 // Work-around for the behavior of throwing from RunAsync not propagating
111 // the exception to the Application.UnhandledException event (as of W8RP)
112 // as our users have come to expect from previous XAML stacks using Rx.
113 //
114 // If we wouldn't do this, there'd be an observable behavioral difference
115 // between scheduling with TimeSpan.Zero or using this overload.
116 //
117 // For scheduler implementation guidance rules, see TaskPoolScheduler.cs
118 // in System.Reactive.PlatformServices\Reactive\Concurrency.
119 //
120 var timer = new DispatcherTimer();
121 timer.Interval = TimeSpan.Zero;
122 timer.Tick += (o, e) =>
123 {
124 timer.Stop();
125 ExceptionDispatchInfo.Capture(ex).Throw();
126 };
127
128 timer.Start();
129 }
130 }
131 });
132
133 return new CompositeDisposable(
134 d,
135 Disposable.Create(res.Cancel)
136 );
137 }
138
139 /// <summary>
140 /// Schedules an action to be executed after dueTime on the dispatcher, using a Windows.UI.Xaml.DispatcherTimer object.
141 /// </summary>
142 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
143 /// <param name="state">State passed to the action to be executed.</param>
144 /// <param name="action">Action to be executed.</param>
145 /// <param name="dueTime">Relative time after which to execute the action.</param>
146 /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns>
147 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
148 public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
149 {
150 if (action == null)
151 throw new ArgumentNullException("action");
152
153 var dt = Scheduler.Normalize(dueTime);
154 if (dt.Ticks == 0)
155 return Schedule(state, action);
156
157 var d = new MultipleAssignmentDisposable();
158
159 var timer = new DispatcherTimer();
160
161 timer.Tick += (o, e) =>
162 {
163 var t = Interlocked.Exchange(ref timer, null);
164 if (t != null)
165 {
166 try
167 {
168 d.Disposable = action(this, state);
169 }
170 finally
171 {
172 t.Stop();
173 action = null;
174 }
175 }
176 };
177
178 timer.Interval = dt;
179 timer.Start();
180
181 d.Disposable = Disposable.Create(() =>
182 {
183 var t = Interlocked.Exchange(ref timer, null);
184 if (t != null)
185 {
186 t.Stop();
187 action = (_, __) => Disposable.Empty;
188 }
189 });
190
191 return d;
192 }
193
194 /// <summary>
195 /// Schedules a periodic piece of work on the dispatcher, using a Windows.UI.Xaml.DispatcherTimer object.
196 /// </summary>
197 /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
198 /// <param name="state">Initial state passed to the action upon the first iteration.</param>
199 /// <param name="period">Period for running the work periodically.</param>
200 /// <param name="action">Action to be executed, potentially updating the state.</param>
201 /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
202 /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
203 /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
204 public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
205 {
206 //
207 // According to MSDN documentation, the default is TimeSpan.Zero, so that's definitely valid.
208 // Empirical observation - negative values seem to be normalized to TimeSpan.Zero, but let's not go there.
209 //
210 if (period < TimeSpan.Zero)
211 throw new ArgumentOutOfRangeException("period");
212 if (action == null)
213 throw new ArgumentNullException("action");
214
215 var timer = new DispatcherTimer();
216
217 var state1 = state;
218
219 timer.Tick += (o, e) =>
220 {
221 state1 = action(state1);
222 };
223
224 timer.Interval = period;
225 timer.Start();
226
227 return Disposable.Create(() =>
228 {
229 var t = Interlocked.Exchange(ref timer, null);
230 if (t != null)
231 {
232 t.Stop();
233 action = _ => _;
234 }
235 });
236 }
237 }
238 }
239 #endif