TpScheduler.cs
Go to the documentation of this file.
1 //
2 // TpScheduler.cs
3 //
4 // Authors:
5 // Jérémie Laval <jeremie dot laval at xamarin dot com>
6 // Marek Safar <marek.safar@gmail.com>
7 //
8 // Copyright (c) 2011 Jérémie "Garuma" Laval
9 // Copyright 2012 Xamarin Inc (http://www.xamarin.com).
10 //
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining a copy
13 // of this software and associated documentation files (the "Software"), to deal
14 // in the Software without restriction, including without limitation the rights
15 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 // copies of the Software, and to permit persons to whom the Software is
17 // furnished to do so, subject to the following conditions:
18 //
19 // The above copyright notice and this permission notice shall be included in
20 // all copies or substantial portions of the Software.
21 //
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 // THE SOFTWARE.
29 //
30 //
31 
32 #if NET_4_0
33 
35 
36 namespace System.Threading.Tasks
37 {
38  sealed class TpScheduler: TaskScheduler
39  {
40  static readonly WaitCallback callback = TaskExecuterCallback;
41 
42  protected internal override void QueueTask (Task task)
43  {
44  if ((task.CreationOptions & TaskCreationOptions.LongRunning) != 0) {
45  var thread = new Thread (l => ((Task)l).Execute ()) {
46  IsBackground = true
47  };
48 
49  thread.Start (task);
50  return;
51  }
52 
53  // Spicy Pixel: This seems to be working on AOT again. If not, use below.
54  // The main difference is that the callstack is not propagated with the
55  // unsafe method which allows for elevated security in the queued task
56  // (which is desirable here).
57  //
58  // Switching back to QueueUserWorkItem as it works with 2.0 subset.
59  // ThreadPool.UnsafeQueueUserWorkItem (callback, task);
60  ThreadPool.QueueUserWorkItem (callback, task);
61  }
62 
63  static void TaskExecuterCallback (object obj)
64  {
65  Task task = (Task)obj;
66  task.Execute ();
67  }
68 
69  protected override IEnumerable<Task> GetScheduledTasks ()
70  {
71  throw new NotImplementedException();
72  }
73 
74  [MonoTODO ("Tasks cannot be dequeued")]
75  protected internal override bool TryDequeue (Task task)
76  {
77  return false;
78  }
79 
80  protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
81  {
82  if (taskWasPreviouslyQueued && !TryDequeue (task))
83  return false;
84 
85  return TryExecuteTask(task);
86  }
87  }
88 }
89 #endif