File: Scheduler.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (654 lines) | stat: -rw-r--r-- 22,137 bytes parent folder | download | duplicates (7)
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.Activities.Runtime
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime;
    using System.Runtime.Serialization;
    using System.Security;
    using System.Threading;
    using System.Runtime.Diagnostics;

    [DataContract(Name = XD.Runtime.Scheduler, Namespace = XD.Runtime.Namespace)]
    class Scheduler
    {
        static ContinueAction continueAction = new ContinueAction();
        static YieldSilentlyAction yieldSilentlyAction = new YieldSilentlyAction();
        static AbortAction abortAction = new AbortAction();

        WorkItem firstWorkItem;

        static SendOrPostCallback onScheduledWorkCallback = Fx.ThunkCallback(new SendOrPostCallback(OnScheduledWork));

        SynchronizationContext synchronizationContext;

        bool isPausing;
        bool isRunning;

        bool resumeTraceRequired;

        Callbacks callbacks;

        Quack<WorkItem> workItemQueue;

        public Scheduler(Callbacks callbacks)
        {
            this.Initialize(callbacks);
        }

        public static RequestedAction Continue
        {
            get
            {
                return continueAction;
            }
        }

        public static RequestedAction YieldSilently
        {
            get
            {
                return yieldSilentlyAction;
            }
        }

        public static RequestedAction Abort
        {
            get
            {
                return abortAction;
            }
        }

        public bool IsRunning
        {
            get
            {
                return this.isRunning;
            }
        }

        public bool IsIdle
        {
            get
            {
                return this.firstWorkItem == null;
            }
        }

        [DataMember(EmitDefaultValue = false, Name = "firstWorkItem")]
        internal WorkItem SerializedFirstWorkItem
        {
            get { return this.firstWorkItem; }
            set { this.firstWorkItem = value; }
        }

        [DataMember(EmitDefaultValue = false)]
        [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode)]
        internal WorkItem[] SerializedWorkItemQueue
        {
            get
            {
                if (this.workItemQueue != null && this.workItemQueue.Count > 0)
                {
                    return this.workItemQueue.ToArray();
                }
                else
                {
                    return null;
                }
            }
            set
            {
                Fx.Assert(value != null, "EmitDefaultValue is false so we should never get null.");

                // this.firstWorkItem is serialized out separately, so don't use ScheduleWork() here
                this.workItemQueue = new Quack<WorkItem>(value);
            }
        }

        public void FillInstanceMap(ActivityInstanceMap instanceMap)
        {
            if (this.firstWorkItem != null)
            {
                ActivityInstanceMap.IActivityReference activityReference = this.firstWorkItem as ActivityInstanceMap.IActivityReference;
                if (activityReference != null)
                {
                    instanceMap.AddEntry(activityReference, true);
                }

                if (this.workItemQueue != null && this.workItemQueue.Count > 0)
                {
                    for (int i = 0; i < this.workItemQueue.Count; i++)
                    {
                        activityReference = this.workItemQueue[i] as ActivityInstanceMap.IActivityReference;
                        if (activityReference != null)
                        {
                            instanceMap.AddEntry(activityReference, true);
                        }
                    }
                }
            }
        }

        public static RequestedAction CreateNotifyUnhandledExceptionAction(Exception exception, ActivityInstance sourceInstance)
        {
            return new NotifyUnhandledExceptionAction(exception, sourceInstance);
        }

        public void ClearAllWorkItems(ActivityExecutor executor)
        {
            if (this.firstWorkItem != null)
            {
                this.firstWorkItem.Release(executor);
                this.firstWorkItem = null;

                if (this.workItemQueue != null)
                {
                    while (this.workItemQueue.Count > 0)
                    {
                        WorkItem item = this.workItemQueue.Dequeue();
                        item.Release(executor);
                    }
                }
            }

            Fx.Assert(this.workItemQueue == null || this.workItemQueue.Count == 0, "We either didn't have a first work item and therefore don't have anything in the queue, or we drained the queue.");

            // For consistency we set this to null even if it is empty
            this.workItemQueue = null;
        }

        public void OnDeserialized(Callbacks callbacks)
        {
            Initialize(callbacks);
            Fx.Assert(this.firstWorkItem != null || this.workItemQueue == null, "cannot have items in the queue unless we also have a firstWorkItem set");
        }

        // This method should only be called when we relinquished the thread but did not
        // complete the operation (silent yield is the current example)
        public void InternalResume(RequestedAction action)
        {
            Fx.Assert(this.isRunning, "We should still be processing work - we just don't have a thread");

            bool isTracingEnabled = FxTrace.ShouldTraceInformation;
            bool notifiedCompletion = false;
            bool isInstanceComplete = false;

            if (this.callbacks.IsAbortPending)
            {
                this.isPausing = false;
                this.isRunning = false;

                this.NotifyWorkCompletion();
                notifiedCompletion = true;

                if (isTracingEnabled)
                {
                    isInstanceComplete = this.callbacks.IsCompleted;
                }

                // After calling SchedulerIdle we no longer have the lock.  That means
                // that any subsequent processing in this method won't have the single
                // threaded guarantee.
                this.callbacks.SchedulerIdle();
            }
            else if (object.ReferenceEquals(action, continueAction))
            {
                ScheduleWork(false);
            }
            else
            {
                Fx.Assert(action is NotifyUnhandledExceptionAction, "This is the only other choice because we should never have YieldSilently here");

                NotifyUnhandledExceptionAction notifyAction = (NotifyUnhandledExceptionAction)action;

                // We only set isRunning back to false so that the host doesn't
                // have to treat this like a pause notification.  As an example,
                // a host could turn around and call run again in response to
                // UnhandledException without having to go through its operation
                // dispatch loop first (or request pause again).  If we reset
                // isPausing here then any outstanding operations wouldn't get
                // signaled with that type of host.
                this.isRunning = false;

                this.NotifyWorkCompletion();
                notifiedCompletion = true;

                if (isTracingEnabled)
                {
                    isInstanceComplete = this.callbacks.IsCompleted;
                }

                this.callbacks.NotifyUnhandledException(notifyAction.Exception, notifyAction.Source);
            }

            if (isTracingEnabled)
            {
                if (notifiedCompletion)
                {
                    Guid oldActivityId = Guid.Empty;
                    bool resetId = false;

                    if (isInstanceComplete)
                    {
                        if (TD.WorkflowActivityStopIsEnabled())
                        {
                            oldActivityId = DiagnosticTraceBase.ActivityId;
                            DiagnosticTraceBase.ActivityId = this.callbacks.WorkflowInstanceId;
                            resetId = true;

                            TD.WorkflowActivityStop(this.callbacks.WorkflowInstanceId);
                        }
                    }
                    else
                    {
                        if (TD.WorkflowActivitySuspendIsEnabled())
                        {
                            oldActivityId = DiagnosticTraceBase.ActivityId;
                            DiagnosticTraceBase.ActivityId = this.callbacks.WorkflowInstanceId;
                            resetId = true;

                            TD.WorkflowActivitySuspend(this.callbacks.WorkflowInstanceId);
                        }
                    }

                    if (resetId)
                    {
                        DiagnosticTraceBase.ActivityId = oldActivityId;
                    }
                }
            }
        }

        // called from ctor and OnDeserialized intialization paths
        void Initialize(Callbacks callbacks)
        {
            this.callbacks = callbacks;
        }

        public void Open(SynchronizationContext synchronizationContext)
        {
            Fx.Assert(this.synchronizationContext == null, "can only open when in the created state");
            if (synchronizationContext != null)
            {
                this.synchronizationContext = synchronizationContext;
            }
            else
            {
                this.synchronizationContext = SynchronizationContextHelper.GetDefaultSynchronizationContext();
            }
        }

        internal void Open(Scheduler oldScheduler)
        {
            Fx.Assert(this.synchronizationContext == null, "can only open when in the created state");
            this.synchronizationContext = SynchronizationContextHelper.CloneSynchronizationContext(oldScheduler.synchronizationContext);
        }

        void ScheduleWork(bool notifyStart)
        {
            if (notifyStart)
            {
                this.synchronizationContext.OperationStarted();
                this.resumeTraceRequired = true;
            }
            else
            {
                this.resumeTraceRequired = false;
            }
            this.synchronizationContext.Post(Scheduler.onScheduledWorkCallback, this);
        }

        void NotifyWorkCompletion()
        {
            this.synchronizationContext.OperationCompleted();
        }

        // signal the scheduler to stop processing work. If we are processing work
        // then we will catch this signal at our next iteration. Pause process completes
        // when idle is signalled. Can be called while we're processing work since
        // the worst thing that could happen in a ---- is that we pause one extra work item later
        public void Pause()
        {
            this.isPausing = true;
        }

        public void MarkRunning()
        {
            this.isRunning = true;
        }

        public void Resume()
        {
            Fx.Assert(this.isRunning, "This should only be called after we've been set to process work.");

            if (this.IsIdle || this.isPausing || this.callbacks.IsAbortPending)
            {
                this.isPausing = false;
                this.isRunning = false;
                this.callbacks.SchedulerIdle();
            }
            else
            {
                ScheduleWork(true);
            }
        }

        public void PushWork(WorkItem workItem)
        {
            if (this.firstWorkItem == null)
            {
                this.firstWorkItem = workItem;
            }
            else
            {
                if (this.workItemQueue == null)
                {
                    this.workItemQueue = new Quack<WorkItem>();
                }

                this.workItemQueue.PushFront(this.firstWorkItem);
                this.firstWorkItem = workItem;
            }

            // To avoid the virt call on EVERY work item we check
            // the Verbose flag.  All of our Schedule traces are
            // verbose.
            if (FxTrace.ShouldTraceVerboseToTraceSource)
            {
                workItem.TraceScheduled();
            }
        }

        public void EnqueueWork(WorkItem workItem)
        {
            if (this.firstWorkItem == null)
            {
                this.firstWorkItem = workItem;
            }
            else
            {
                if (this.workItemQueue == null)
                {
                    this.workItemQueue = new Quack<WorkItem>();
                }

                this.workItemQueue.Enqueue(workItem);
            }

            if (FxTrace.ShouldTraceVerboseToTraceSource)
            {
                workItem.TraceScheduled();
            }
        }

        static void OnScheduledWork(object state)
        {
            Scheduler thisPtr = (Scheduler)state;

            // We snapshot these values here so that we can
            // use them after calling OnSchedulerIdle.
            bool isTracingEnabled = FxTrace.Trace.ShouldTraceToTraceSource(TraceEventLevel.Informational);
            Guid oldActivityId = Guid.Empty;
            Guid workflowInstanceId = Guid.Empty;

            if (isTracingEnabled)
            {
                oldActivityId = DiagnosticTraceBase.ActivityId;
                workflowInstanceId = thisPtr.callbacks.WorkflowInstanceId;
                FxTrace.Trace.SetAndTraceTransfer(workflowInstanceId, true);

                if (thisPtr.resumeTraceRequired)
                {
                    if (TD.WorkflowActivityResumeIsEnabled())
                    {
                        TD.WorkflowActivityResume(workflowInstanceId);
                    }
                }
            }

            thisPtr.callbacks.ThreadAcquired();

            RequestedAction nextAction = continueAction;
            bool idleOrPaused = false;

            while (object.ReferenceEquals(nextAction, continueAction))
            {
                if (thisPtr.IsIdle || thisPtr.isPausing)
                {
                    idleOrPaused = true;
                    break;
                }

                // cycle through (queue->thisPtr.firstWorkItem->currentWorkItem)
                WorkItem currentWorkItem = thisPtr.firstWorkItem;

                // promote an item out of our work queue if necessary
                if (thisPtr.workItemQueue != null && thisPtr.workItemQueue.Count > 0)
                {
                    thisPtr.firstWorkItem = thisPtr.workItemQueue.Dequeue();
                }
                else
                {
                    thisPtr.firstWorkItem = null;
                }

                if (TD.ExecuteWorkItemStartIsEnabled())
                {
                    TD.ExecuteWorkItemStart();
                }

                nextAction = thisPtr.callbacks.ExecuteWorkItem(currentWorkItem);

                if (TD.ExecuteWorkItemStopIsEnabled())
                {
                    TD.ExecuteWorkItemStop();
                }
            }

            bool notifiedCompletion = false;
            bool isInstanceComplete = false;

            if (idleOrPaused || object.ReferenceEquals(nextAction, abortAction))
            {
                thisPtr.isPausing = false;
                thisPtr.isRunning = false;

                thisPtr.NotifyWorkCompletion();
                notifiedCompletion = true;

                if (isTracingEnabled)
                {
                    isInstanceComplete = thisPtr.callbacks.IsCompleted;
                }

                // After calling SchedulerIdle we no longer have the lock.  That means
                // that any subsequent processing in this method won't have the single
                // threaded guarantee.
                thisPtr.callbacks.SchedulerIdle();
            }
            else if (!object.ReferenceEquals(nextAction, yieldSilentlyAction))
            {
                Fx.Assert(nextAction is NotifyUnhandledExceptionAction, "This is the only other option");

                NotifyUnhandledExceptionAction notifyAction = (NotifyUnhandledExceptionAction)nextAction;

                // We only set isRunning back to false so that the host doesn't
                // have to treat this like a pause notification.  As an example,
                // a host could turn around and call run again in response to
                // UnhandledException without having to go through its operation
                // dispatch loop first (or request pause again).  If we reset
                // isPausing here then any outstanding operations wouldn't get
                // signaled with that type of host.
                thisPtr.isRunning = false;

                thisPtr.NotifyWorkCompletion();
                notifiedCompletion = true;

                if (isTracingEnabled)
                {
                    isInstanceComplete = thisPtr.callbacks.IsCompleted;
                }

                thisPtr.callbacks.NotifyUnhandledException(notifyAction.Exception, notifyAction.Source);
            }

            if (isTracingEnabled)
            {
                if (notifiedCompletion)
                {
                    if (isInstanceComplete)
                    {
                        if (TD.WorkflowActivityStopIsEnabled())
                        {
                            TD.WorkflowActivityStop(workflowInstanceId);
                        }
                    }
                    else
                    {
                        if (TD.WorkflowActivitySuspendIsEnabled())
                        {
                            TD.WorkflowActivitySuspend(workflowInstanceId);
                        }
                    }
                }

                DiagnosticTraceBase.ActivityId = oldActivityId;
            }
        }

        public struct Callbacks
        {
            readonly ActivityExecutor activityExecutor;

            public Callbacks(ActivityExecutor activityExecutor)
            {
                this.activityExecutor = activityExecutor;
            }

            public Guid WorkflowInstanceId
            {
                get
                {
                    return this.activityExecutor.WorkflowInstanceId;
                }
            }

            public bool IsAbortPending
            {
                get
                {
                    return this.activityExecutor.IsAbortPending || this.activityExecutor.IsTerminatePending;
                }
            }

            public bool IsCompleted
            {
                get
                {
                    return ActivityUtilities.IsCompletedState(this.activityExecutor.State);
                }
            }

            public RequestedAction ExecuteWorkItem(WorkItem workItem)
            {
                Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in ExecuteWorkItem.");

                // We check the Verbose flag to avoid the 
                // virt call if possible
                if (FxTrace.ShouldTraceVerboseToTraceSource)
                {
                    workItem.TraceStarting();
                }

                RequestedAction action = this.activityExecutor.OnExecuteWorkItem(workItem);

                if (!object.ReferenceEquals(action, Scheduler.YieldSilently))
                {
                    if (this.activityExecutor.IsAbortPending || this.activityExecutor.IsTerminatePending)
                    {
                        action = Scheduler.Abort;
                    }

                    // if the caller yields, then the work item is still active and the callback
                    // is responsible for releasing it back to the pool                    
                    workItem.Dispose(this.activityExecutor);                    
                }

                return action;
            }

            public void SchedulerIdle()
            {
                Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in SchedulerIdle.");
                this.activityExecutor.OnSchedulerIdle();
            }

            public void ThreadAcquired()
            {
                Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in ThreadAcquired.");
                this.activityExecutor.OnSchedulerThreadAcquired();
            }

            public void NotifyUnhandledException(Exception exception, ActivityInstance source)
            {
                Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in NotifyUnhandledException.");
                this.activityExecutor.NotifyUnhandledException(exception, source);
            }
        }

        internal abstract class RequestedAction
        {
            protected RequestedAction()
            {
            }
        }

        class ContinueAction : RequestedAction
        {
            public ContinueAction()
            {
            }
        }

        class YieldSilentlyAction : RequestedAction
        {
            public YieldSilentlyAction()
            {
            }
        }

        class AbortAction : RequestedAction
        {
            public AbortAction()
            {
            }
        }

        class NotifyUnhandledExceptionAction : RequestedAction
        {
            public NotifyUnhandledExceptionAction(Exception exception, ActivityInstance source)
            {
                this.Exception = exception;
                this.Source = source;
            }

            public Exception Exception
            {
                get;
                private set;
            }

            public ActivityInstance Source
            {
                get;
                private set;
            }
        }
    }
}