My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
using System;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;

// the classes in this file are intended to illustrate a bespoke awaiter implementation - nothing more, nothing less
namespace Async
{
class MonitorPool
{
private readonly object[] pool;
public MonitorPool(int length)
{
this.pool = new object[length];
}
public object Get()
{
object obj;
for (int i = 0; i < pool.Length; i++)
{
if ((obj = Interlocked.Exchange(ref pool[i], null)) != null) return obj; // found something useful
}
return new object();
}
public void Return(object obj)
{
if (obj != null)
{
for (int i = 0; i < pool.Length; i++)
{
if (Interlocked.CompareExchange(ref pool[i], obj, null) == null) return; // found an empty slot
}
}
// just drop it on the floor
}
}

class CustomAwaiter
{
public static void Execute()
{
#pragma warning disable 0618
Future<int>[] futures = new Future<int>[10];
MonitorPool pool = new MonitorPool(futures.Length);
const int loop = 500000;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
var watch = Stopwatch.StartNew();
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
futures[i] = new Future<int>(syncLock: pool.Get());
}
for (int i = 0; i < futures.Length; i++)
{
pool.Return(futures[i].OnSuccess(i+1));
}
for (int i = 0; i < futures.Length; i++)
{
if (futures[i].Result != i+1) throw new InvalidOperationException();
}
}
watch.Stop();

Console.WriteLine("Future (uncontested): " + watch.ElapsedMilliseconds);
#pragma warning restore 0618
Task<int>[] tasks = new Task<int>[futures.Length];
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
watch = Stopwatch.StartNew();
Func<object, int> selector = state => (int)state;
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
tasks[i] = new Task<int>(selector, i+1);
}
for (int i = 0; i < futures.Length; i++)
{
tasks[i].RunSynchronously(TaskScheduler.Default);
}
for (int i = 0; i < futures.Length; i++)
{
if (tasks[i].Result != i+1) throw new InvalidOperationException();
}
}
watch.Stop();

Console.WriteLine("Task (uncontested): " + watch.ElapsedMilliseconds);
TaskCompletionSource<int>[] sources = new TaskCompletionSource<int>[futures.Length];
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
watch = Stopwatch.StartNew();
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
sources[i] = new TaskCompletionSource<int>();
}
for (int i = 0; i < futures.Length; i++)
{
sources[i].SetResult(i+1);
}
for (int i = 0; i < futures.Length; i++)
{
if (sources[i].Task.Result != i + 1) throw new InvalidOperationException();
}
}
watch.Stop();

Console.WriteLine("Source (uncontested): " + watch.ElapsedMilliseconds);
#pragma warning disable 0618
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
watch = Stopwatch.StartNew();
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
futures[i] = new Future<int>(syncLock: pool.Get());
}
ThreadPool.QueueUserWorkItem(delegate
{
for (int i = 0; i < futures.Length; i++)
{
pool.Return(futures[i].OnSuccess(i+1));
}
});
for (int i = 0; i < futures.Length; i++)
{
int x = futures[i].Result;
if (x != i+1)
{
throw new InvalidOperationException(string.Format("{0} instead of {1}", x, i+1));
}
}
}
watch.Stop();
#pragma warning restore 0618
Console.WriteLine("Future (contested): " + watch.ElapsedMilliseconds);

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
watch = Stopwatch.StartNew();
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
tasks[i] = new Task<int>(selector, i+1);
}
ThreadPool.QueueUserWorkItem(delegate
{
for (int i = 0; i < futures.Length; i++)
{
tasks[i].RunSynchronously(TaskScheduler.Default);
}
});
for (int i = 0; i < futures.Length; i++)
{
if (tasks[i].Result != i+1) throw new InvalidOperationException();
}
}
watch.Stop();

Console.WriteLine("Task (contested): " + watch.ElapsedMilliseconds);


GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
watch = Stopwatch.StartNew();
for (int j = 0; j < loop; j++)
{
for (int i = 0; i < futures.Length; i++)
{
sources[i] = new TaskCompletionSource<int>();
}
ThreadPool.QueueUserWorkItem(delegate
{
for (int i = 0; i < futures.Length; i++)
{
sources[i].SetResult(i+1);
}
});
for (int i = 0; i < futures.Length; i++)
{
if (sources[i].Task.Result != i + 1) throw new InvalidOperationException();
}
}
watch.Stop();

Console.WriteLine("Source (contested): " + watch.ElapsedMilliseconds);
}


static void Main2()
{
#pragma warning disable 0618
var typed = new Future<int>();
Future untyped = typed;
#pragma warning restore 0618
DoSomet(typed);
DoSomet(untyped);
ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(5000);
Console.WriteLine("setting...");
object gotBack = typed.OnSuccess(123);
Console.WriteLine("set; " + (gotBack == null ? "nothing" : "syncLock"));
});
untyped.Wait();
int i = typed.Result;
Console.WriteLine("sync: " + i);
Console.ReadLine();
}
#pragma warning disable 0618
static async void DoSomet(Future obj)
{

await obj;
Console.WriteLine("async");
}
static async void DoSomet(Future<int> obj)
{
var i = await obj;
Console.WriteLine("async: " + i);
}
#pragma warning restore 0618
}

public interface IFutureAwaiter
{
/// <summary>
/// Has the operation completed?
/// </summary>
bool IsCompleted { get; }
/// <summary>
/// Register an operation to perform when the operation has comleted; if it has *already*
/// completed this operation is performed immediately.
/// </summary>
void OnCompleted(Action callback);
/// <summary>
/// Assert successful completion of the operation; if the operation completed with error, the exception
/// is propegated. If the operation has not yet completed this will block.
/// </summary>
void GetResult();
}
public interface IFutureAwaiter<T>
{
/// <summary>
/// Has the operation completed?
/// </summary>
bool IsCompleted { get; }
/// <summary>
/// Register an operation to perform when the operation has comleted; if it has *already*
/// completed this operation is performed immediately.
/// </summary>
void OnCompleted(Action callback);
/// <summary>
/// Assert successful completion of the operation; if the operation completed with error, the exception
/// is propegated; otherwise the specified result is returned. If no result was specified then
/// the default value of T is returned.
/// If the operation has not yet completed this will block.
/// </summary>
T GetResult();
}


/// <summary>
/// Represents an asynchronous operation without a return value; this may have completed already, or may complete at any time.
/// Both synchronous (blocking) operations and asynchronous (continuation) operations are supported.
/// </summary>
/// <remarks>All members on this class are thread-safe.</remarks>
[Obsolete("DO NOT USE THIS; TaskCompletionSource<T> is preferred")]
public class Future : IFutureAwaiter
{
/// <summary>
/// Create a new Future object
/// </summary>
/// <param name="millisecondsTimeout">The time to wait in GetResult beore a TimeoutException is thrown</param>
/// <param name="syncLock">The object to use as for use with Monitor; if none is supplied a new object
/// is created for the purpose.</param>
public Future(int millisecondsTimeout = int.MaxValue, object syncLock = null)
{
this.syncLock = syncLock ?? new object();
this.millisecondsTimeout = millisecondsTimeout;
}
private readonly int millisecondsTimeout;
private Exception exception;
private object syncLock;
/// <summary>
/// Returns an "awaiter" for use with async/await
/// </summary>
public IFutureAwaiter GetAwaiter() { return this;}
private Action callbacks;
/// <summary>
/// Has the operation completed?
/// </summary>
public bool IsCompleted {
get {
return syncLock == null;
// Interlocked would be more accurate; but the flip is atomic, at least, so
// we'll accept the *unlikely* chance of a misread, and absorb that into OnCompleted
}
}

void IFutureAwaiter.OnCompleted(Action callback)
{
if (callback == null) return; // nothing to do
object localLock;

if (syncLock == null || (localLock = Interlocked.CompareExchange(ref syncLock, null, null)) == null)
{
callback(); // has already completed
return;
}

lock (localLock)
{
if (syncLock == null)
{
// completed *just now*
callback();
return;
}

// enqueue that work
callbacks += callback;
}
}

/// <summary>
/// Assert successful completion of the operation; if the operation completed with error, the exception
/// is propegated. If the operation has not yet completed this will block.
/// </summary>
public void Wait()
{
object localLock;
if (syncLock == null || (localLock = Interlocked.CompareExchange(ref syncLock, null, null)) == null)
{
// already completed
Thread.MemoryBarrier();
if (exception != null) throw exception;
return;
}

bool completed;
lock (localLock)
{
completed = syncLock == null; // true if completed *just now*

if (!completed)
{
completed = Monitor.Wait(localLock, millisecondsTimeout);
}
}
if (completed)
{
// completed while we were waiting
if (exception != null) throw exception;
}
else
{
throw new TimeoutException(); // took too long
}
}
void IFutureAwaiter.GetResult()
{
Wait();
}
/// <summary>
/// Signals that the operation has completed successfully.
/// </summary>
/// <returns>The object being used for Monitor locking is returned, and should
/// now (if non-null) be avaialble for re-use if desired</returns>
public object OnSuccess()
{
int tmp = 0;
return OnComplete(ref tmp, 0);
}
/// <summary>
/// Signals that the operation has completed with error
/// </summary>
/// <param name="exception">The exception encountered</param>
/// <returns>The object being used for Monitor locking is returned, and should
/// now (if non-null) be avaialble for re-use if desired</returns>
public object OnFailure(Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
return OnComplete(ref this.exception, exception);
}
/// <summary>
/// Signals that the operation has completed, allowing auxiliary data to be set
/// </summary>
/// <typeparam name="T">The type of auxiliary data to set</typeparam>
/// <param name="field">The auxiliary field to assign (after checks and inside suitable synchronization, etc)</param>
/// <param name="value">The new value to assign to the auxiliary field</param>
/// <returns>The object being used for Monitor locking is returned, and should
/// now (if non-null) be avaialble for re-use if desired</returns>
protected object OnComplete<T>(ref T field, T value)
{
object localLock = Interlocked.CompareExchange(ref syncLock, null, null);
if (localLock == null)
{
throw new InvalidOperationException("The Future is already completed");
}
Action callbacks;
lock (localLock)
{
// need to use Interlocked here, since that is what the other readers are using
if (Interlocked.CompareExchange(ref syncLock, null, null) == null)
{
throw new InvalidOperationException("The Future is already completed");
}
field = value;
Interlocked.Exchange(ref syncLock, null);

Monitor.PulseAll(localLock); // open up for sync waiters

callbacks = this.callbacks;
this.callbacks = null; // release for GC
}
if (callbacks != null)
{ // invoke async waiters
foreach (Action action in callbacks.GetInvocationList())
{
try
{
action();
}
catch (Exception ex)
{
var handler = CallbackException;
if (handler != null) { handler(ex); }
}
}
}
return localLock;
}
/// <summary>
/// Global event that signals exceptions encountered signalling callbacks
/// </summary>
public static event Action<Exception> CallbackException;
}
/// <summary>
/// Represents an asynchronous operation with a return value; this may have completed already, or may complete at any time.
/// Both synchronous (blocking) operations and asynchronous (continuation) operations are supported.
/// </summary>
/// <remarks>All members on this class are thread-safe.</remarks>
[Obsolete("DO NOT USE THIS; TaskCompletionSource<T> is preferred")]
#pragma warning disable 0618
public sealed class Future<T> : Future, IFutureAwaiter<T>
{
#pragma warning restore 0618
/// <summary>
/// Create a new Future object
/// </summary>
/// <param name="millisecondsTimeout">The time to wait in GetResult beore a TimeoutException is thrown</param>
/// <param name="syncLock">The object to use as for use with Monitor; if none is supplied a new object
/// is created for the purpose.</param>
public Future(int millisecondsTimeout = int.MaxValue, object syncLock = null) : base(millisecondsTimeout, syncLock)
{ }

/// <summary>
/// Returns an "awaiter" for use with async/await
/// </summary>
public new IFutureAwaiter<T> GetAwaiter() { return this;}
private T result;

void IFutureAwaiter<T>.OnCompleted(Action callback)
{
((IFutureAwaiter)this).OnCompleted(callback);
}

T IFutureAwaiter<T>.GetResult()
{
return Result;
}
/// <summary>
/// Assert successful completion of the operation; if the operation completed with error, the exception
/// is propegated; otherwise the specified result is returned. If no result was specified then
/// the default value of T is returned.
/// If the operation has not yet completed this will block.
/// </summary>
public T Result
{
get
{
Wait();
return result;
}
}

/// <summary>
/// Signals that the operation has completed successfully, assigning a result value.
/// </summary>
/// <returns>The object being used for Monitor locking is returned, and should
/// now (if non-null) be avaialble for re-use if desired</returns>
public object OnSuccess(T result)
{
return OnComplete(ref this.result, result);
}
}
}

Change log

1d064884594c by mgravell on Apr 29, 2011   Diff
0.9 prep
Go to: 
Project members, sign in to write a code review

Older revisions

3e777125f0c2 by mgravell on Apr 27, 2011   Diff
introduce TaskCompletionSource<T>
701ff5464efd by mgravell on Apr 25, 2011   Diff
handle failure events; add
customawaiter example
All revisions of this file

File info

Size: 19590 bytes, 504 lines
Powered by Google Project Hosting