File: BackgroundWorkScheduler.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 (114 lines) | stat: -rw-r--r-- 4,922 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
//------------------------------------------------------------------------------
// <copyright file="BackgroundWorkScheduler.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

namespace System.Web.Hosting {
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web.Util;

    internal sealed class BackgroundWorkScheduler : IRegisteredObject {

        private readonly CancellationTokenHelper _cancellationTokenHelper = new CancellationTokenHelper(canceled: false);
        private int _numExecutingWorkItems; // number of executing work items, not scheduled work items; a work item might never be scheduled
        private readonly Action<BackgroundWorkScheduler> _unregisterCallback;
        private readonly Action<AppDomain, Exception> _logCallback;
        private readonly Action _workItemCompleteCallback;

        internal BackgroundWorkScheduler(Action<BackgroundWorkScheduler> unregisterCallback, Action<AppDomain, Exception> logCallback, Action workItemCompleteCallback = null) {
            Debug.Assert(unregisterCallback != null);
            _unregisterCallback = unregisterCallback;
            _logCallback = logCallback;
            _workItemCompleteCallback = workItemCompleteCallback;
        }

        private void FinalShutdown() {
            _unregisterCallback(this);
        }

        // we can use 'async void' here since we're guaranteed to be off the AspNetSynchronizationContext
        private async void RunWorkItemImpl(Func<CancellationToken, Task> workItem) {
            Task returnedTask = null;
            try {
                returnedTask = workItem(_cancellationTokenHelper.Token);
                await returnedTask.ConfigureAwait(continueOnCapturedContext: false);
            }
            catch (Exception ex) {
                // ---- exceptions caused by the returned task being canceled
                if (returnedTask != null && returnedTask.IsCanceled) {
                    return;
                }

                // ---- exceptions caused by CancellationToken.ThrowIfCancellationRequested()
                OperationCanceledException operationCanceledException = ex as OperationCanceledException;
                if (operationCanceledException != null && operationCanceledException.CancellationToken == _cancellationTokenHelper.Token) {
                    return;
                }

                _logCallback(AppDomain.CurrentDomain, ex); // method shouldn't throw
            }
            finally {
                WorkItemComplete();
            }
        }

        public void ScheduleWorkItem(Func<CancellationToken, Task> workItem) {
            Debug.Assert(workItem != null);

            if (_cancellationTokenHelper.IsCancellationRequested) {
                return; // we're not going to run this work item
            }

            // Unsafe* since we want to get rid of Principal and other constructs specific to the current ExecutionContext
            ThreadPool.UnsafeQueueUserWorkItem(state => {
                lock (this) {
                    if (_cancellationTokenHelper.IsCancellationRequested) {
                        return; // we're not going to run this work item
                    }
                    else {
                        _numExecutingWorkItems++;
                    }
                }

                RunWorkItemImpl((Func<CancellationToken, Task>)state);
            }, workItem);
        }

        public void Stop(bool immediate) {
            // Hold the lock for as little time as possible
            int currentWorkItemCount;
            lock (this) {
                _cancellationTokenHelper.Cancel(); // dispatched onto a new thread
                currentWorkItemCount = _numExecutingWorkItems;
            }

            if (currentWorkItemCount == 0) {
                // There was no scheduled work, so we're done
                FinalShutdown();
            }
        }

        private void WorkItemComplete() {
            // Hold the lock for as little time as possible
            int newWorkItemCount;
            bool isCancellationRequested;
            lock (this) {
                newWorkItemCount = --_numExecutingWorkItems;
                isCancellationRequested = _cancellationTokenHelper.IsCancellationRequested;
            }

            // for debugging & unit tests
            if (_workItemCompleteCallback != null) {
                _workItemCompleteCallback();
            }

            if (newWorkItemCount == 0 && isCancellationRequested) {
                // Cancellation was requested, and we were the last work item to complete, so everybody is finished
                FinalShutdown();
            }
        }
    }
}