Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
ChannelMicroThreadAwaiter.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;
4 using System.Collections.Generic;
5 using System.Runtime.CompilerServices;
6 
7 namespace SiliconStudio.Core.MicroThreading
8 {
9  public class ChannelMicroThreadAwaiter<T> : ICriticalNotifyCompletion
10  {
11  private static List<ChannelMicroThreadAwaiter<T>> pool = new List<ChannelMicroThreadAwaiter<T>>();
12 
13  private bool isCompleted = false;
14 
15  internal MicroThread MicroThread;
16  internal Action Continuation;
17  internal T Result;
18 
19  public static ChannelMicroThreadAwaiter<T> New(MicroThread microThread)
20  {
21  lock (pool)
22  {
23  if (pool.Count > 0)
24  {
25  var index = pool.Count - 1;
26  var lastItem = pool[index];
27  pool.RemoveAt(index);
28 
29  lastItem.MicroThread = microThread;
30 
31  return lastItem;
32  }
33 
34  return new ChannelMicroThreadAwaiter<T>(microThread);
35  }
36  }
37 
39  {
40  MicroThread = microThread;
41  }
42 
44  {
45  return this;
46  }
47 
48  public void OnCompleted(Action continuation)
49  {
50  Continuation = continuation;
51  }
52 
53  public void UnsafeOnCompleted(Action continuation)
54  {
55  Continuation = continuation;
56  }
57 
58  public T GetResult()
59  {
60  // Check Task Result (exception, etc...)
61  var result = Result;
62 
63  // After result has been taken, we can reuse this item, so put it in the pool
64  // We mitigate pool size, but another approach than hard limit might be interesting
65  lock (pool)
66  {
67  if (pool.Count < 4096)
68  {
69  isCompleted = false;
70  MicroThread = null;
71  Continuation = null;
72  Result = default(T);
73  }
74 
75  pool.Add(this);
76  }
77 
78  return result;
79  }
80 
81  public bool IsCompleted
82  {
83  get { return isCompleted; }
84  set { isCompleted = value; }
85  }
86  }
87 }
Represents an execution context managed by a Scheduler, that can cooperatively yield execution to ano...
Definition: MicroThread.cs:16
static ChannelMicroThreadAwaiter< T > New(MicroThread microThread)