Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
AsyncSignal.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System.Collections.Generic;
4 using System.Threading.Tasks;
5 
6 #if NET45
7 using TaskEx = System.Threading.Tasks.Task;
8 #endif
9 
10 namespace SiliconStudio.Core.MicroThreading
11 {
12  public class AsyncSignal
13  {
14  private TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
15 
16  public Task WaitAsync()
17  {
18  lock (this)
19  {
20  tcs = new TaskCompletionSource<bool>();
21  var result = tcs.Task;
22  return result;
23  }
24  }
25 
26  public void Set()
27  {
28  lock (this)
29  {
30  tcs.TrySetResult(true);
31  }
32  }
33  }
34 
35  public class AsyncAutoResetEvent
36  {
37  // Credit: http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266923.aspx
38  private readonly static Task completed = TaskEx.FromResult(true);
39  private readonly Queue<TaskCompletionSource<bool>> waits = new Queue<TaskCompletionSource<bool>>();
40  private bool signaled;
41 
42  public Task WaitAsync()
43  {
44  lock (waits)
45  {
46  if (signaled)
47  {
48  signaled = false;
49  return completed;
50  }
51  else
52  {
53  var tcs = new TaskCompletionSource<bool>();
54  waits.Enqueue(tcs);
55  return tcs.Task;
56  }
57  }
58  }
59 
60  public void Set()
61  {
62  TaskCompletionSource<bool> toRelease = null;
63  lock (waits)
64  {
65  if (waits.Count > 0)
66  toRelease = waits.Dequeue();
67  else if (!signaled)
68  signaled = true;
69  }
70  if (toRelease != null)
71  toRelease.SetResult(true);
72  }
73  }
74 
75 }
System.Threading.Tasks.Task Task