Welcome to mirror list, hosted at ThFree Co, Russian Federation.

WorkerThread.cs « Utility « Library « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 383c999de8feb12b8b444fe5b0f9775692ba1599 (plain)
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
#region Disclaimer / License
// Copyright (C) 2010, Kenneth Skovhede
// http://www.hexad.dk, opensource@hexad.dk
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Duplicati.Library.Utility
{
    /// <summary>
    /// Class to encapsulate a thread that runs a list of queued operations
    /// </summary>
    /// <typeparam name="Tx">The type to operate on</typeparam>
    public class WorkerThread<Tx> where Tx : class
    {
        /// <summary>
        /// Locking object for shared data
        /// </summary>
        private object m_lock = new object();
        /// <summary>
        /// The wait event
        /// </summary>
        private AutoResetEvent m_event;
        /// <summary>
        /// The internal list of tasks to perform
        /// </summary>
        private Queue<Tx> m_tasks;
        /// <summary>
        /// A flag used to terminate the thread
        /// </summary>
        private volatile bool m_terminate;
        /// <summary>
        /// The coordinating thread
        /// </summary>
        private Thread m_thread;

        /// <summary>
        /// A value indicating if the coordinating thread is running
        /// </summary>
        private volatile bool m_active;

        /// <summary>
        /// The current task being processed
        /// </summary>
        private Tx m_currentTask;
        /// <summary>
        /// A callback that performs the actual work on the item
        /// </summary>
        private Action<Tx> m_delegate;

        /// <summary>
        /// An event that is raised when the runner state changes
        /// </summary>
        public event Action<WorkerThread<Tx>, RunState> WorkerStateChanged;

        /// <summary>
        /// Event that occurs when a new operation is being processed
        /// </summary>
        public event Action<WorkerThread<Tx>, Tx> StartingWork;
        /// <summary>
        /// Event that occurs when an operation has completed
        /// </summary>
        public event Action<WorkerThread<Tx>, Tx> CompletedWork;
        /// <summary>
        /// Event that occurs when an error is detected
        /// </summary>
        public event Action<WorkerThread<Tx>, Tx, Exception> OnError;
        /// <summary>
        /// An evnet that occurs when a new task is added to the queue or an existing one is removed
        /// </summary>
        public event Action<WorkerThread<Tx>> WorkQueueChanged;

        /// <summary>
        /// The internal state
        /// </summary>
        private volatile RunState m_state;

        /// <summary>
        /// The states the scheduler can take
        /// </summary>
        public enum RunState
        {
            /// <summary>
            /// The program is running as normal
            /// </summary>
            Run,
            /// <summary>
            /// The program is suspended by the user
            /// </summary>
            Paused
        }

        /// <summary>
        /// Constructs a new WorkerThread
        /// </summary>
        /// <param name="item">The callback that performs the work</param>
        public WorkerThread(Action<Tx> item, bool paused)
        {
            m_delegate = item;
            m_event = new AutoResetEvent(paused);
            m_terminate = false;
            m_tasks = new Queue<Tx>();
            m_state = paused ? WorkerThread<Tx>.RunState.Paused : WorkerThread<Tx>.RunState.Run;

            m_thread = new Thread(new ThreadStart(Runner));
            m_thread.IsBackground = true;
            m_thread.Name = "WorkerThread<" + typeof(Tx).Name + ">";
            m_thread.Start();
        }

        /// <summary>
        /// Gets a copy of the current queue
        /// </summary>
        public List<Tx> CurrentTasks
        {
            get
            {
                lock(m_lock)
                    return new List<Tx>(m_tasks);
            }

        }

        /// <summary>
        /// Gets a value indicating if the worker is running
        /// </summary>
        public bool Active
        {
            get { return m_active; }
        }

        /// <summary>
        /// Adds a task to the queue
        /// </summary>
        /// <param name="task">The task to add</param>
        public void AddTask(Tx task)
        {
            lock (m_lock)
            {
                m_tasks.Enqueue(task);
                m_event.Set();
            }

            if (WorkQueueChanged != null)
                WorkQueueChanged(this);
        }

        /// <summary>
        /// Removes a task from the queue, does not remove the task if it is currently running
        /// </summary>
        /// <param name="task">The task to remove</param>
        public void RemoveTask(Tx task)
        {
            lock (m_lock)
            {
                Queue<Tx> tmp = new Queue<Tx>();
                while (m_tasks.Count > 0)
                {
                    Tx n = m_tasks.Dequeue();
                    if (n != task)
                        tmp.Enqueue(n);
                }

                m_tasks = tmp;
            }

            if (WorkQueueChanged != null)
                WorkQueueChanged(this);
        }

        /// <summary>
        /// This will clear the pending queue
        /// <param name="abortThread">True if the current running thread should be aborted</param>
        /// </summary>
        public void ClearQueue(bool abortThread)
        {
            lock (m_lock)
                m_tasks.Clear();

            if (abortThread)
            {
                try
                {
                    m_thread.Abort();
                    m_thread.Join(500);
                }
                catch
                {
                }

                m_thread = new Thread(new ThreadStart(Runner));
                m_thread.Start();
            }
        }

        /// <summary>
        /// Gets a reference to the currently executing task.
        /// BEWARE: This is not protected by a mutex, DO NOT MODIFY IT!!!!
        /// </summary>
        public Tx CurrentTask
        {
            get
            {
                return m_currentTask;
            }
        }

        /// <summary>
        /// Terminates the thread. Any items still in queue will be removed
        /// </summary>
        /// <param name="wait">True if the call should block until the thread has exited, false otherwise</param>
        public void Terminate(bool wait)
        {
            m_terminate = true;
            m_event.Set();

            if (wait)
                m_thread.Join();
        }

        /// <summary>
        /// This is the thread entry point
        /// </summary>
        private void Runner()
        {
            while (!m_terminate)
            {
                m_currentTask = null;

                lock(m_lock)
                    if (m_state == WorkerThread<Tx>.RunState.Run && m_tasks.Count > 0)
                        m_currentTask = m_tasks.Dequeue();

                if (m_currentTask == null && !m_terminate)
                if (m_state == WorkerThread<Tx>.RunState.Run)
                    m_event.WaitOne(); //Sleep until signaled
                    else
                {
                    if (WorkerStateChanged != null)
                        WorkerStateChanged(this, m_state);

                    //Sleep for brief periods, until signaled
                    while (!m_terminate && m_state != WorkerThread<Tx>.RunState.Run)
                        m_event.WaitOne(1000 * 60 * 5, false);

                    //If we were not terminated, we are now ready to run
                    if (!m_terminate)
                    {
                        m_state = WorkerThread<Tx>.RunState.Run;
                        if (WorkerStateChanged != null)
                            WorkerStateChanged(this, m_state);
                    }
                }

                if (m_terminate)
                    return;

                if (m_currentTask == null && m_state == WorkerThread<Tx>.RunState.Run)
                    lock(m_lock)
                        if (m_tasks.Count > 0)
                            m_currentTask = m_tasks.Dequeue();

                if (m_currentTask == null)
                    continue;

                if (StartingWork != null)
                    StartingWork(this, m_currentTask);

                try
                {
                    m_active = true;
                    m_delegate(m_currentTask);
                }
                catch (Exception ex)
                {
                    System.Threading.Thread.ResetAbort(); 
                    if (OnError != null)
                        try { OnError(this, m_currentTask, ex); }
                        catch { }
                }
                finally
                {
                    System.Threading.Thread.ResetAbort(); 
                    m_active = false;
                }

                var task = m_currentTask;
                m_currentTask = null;

                if (CompletedWork != null)
                    try { CompletedWork(this, task); }
                    catch (Exception ex) 
                    {
                        try { OnError(this, task, ex); }
                        catch { }
                    }
            }
        }

        /// <summary>
        /// Gets the current run state
        /// </summary>
        public RunState State { get { return m_state; } }

        /// <summary>
        /// Instructs Duplicati to run scheduled backups
        /// </summary>
        public void Resume()
        {
            m_state = RunState.Run;
            m_event.Set();
        }

        /// <summary>
        /// Instructs Duplicati to pause scheduled backups
        /// </summary>
        public void Pause()
        {
            m_state = RunState.Paused;
            m_event.Set();
        }

        /// <summary>
        /// Waits the specified number of milliseconds for the thread to terminate
        /// </summary>
        /// <param name="millisecondTimeout">The number of milliseconds to wait</param>
        /// <returns>True if the thread is terminated, false if a timeout occured</returns>
        public bool Join(int millisecondTimeout)
        {
            if (m_thread != null)
                return m_thread.Join(millisecondTimeout);
            return true;
        }
    }
}