History

Renamed folders and separated GSF.Media and GSF.Net into separate projects.

StephenCWills committed 14 years ago

Commit ac1ef661 parent 45bce55628 files · +733 −461Browse files

Showing the changes to Source/Libraries/GSF.Core/Threading/ManagedThreads.cs (1 of 628 files). Show all

Unified · Split

Source/Libraries/GSF.Core/Threading/ManagedThreads.cs+442−0
@@ -0,0 +1,442 @@
1//*******************************************************************************************************
2// ManagedThreads.cs - Gbtc
3//
4// Tennessee Valley Authority, 2009
5// No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8//
9// Code Modification History:
10// -----------------------------------------------------------------------------------------------------
11// 01/25/2008 - J. Ritchie Carroll
12// Initial version of source generated.
13// 09/11/2008 - J. Ritchie Carroll
14// Converted to C#.
15// 09/14/2009 - Stephen C. Wills
16// Added new header and license agreement.
17//
18//*******************************************************************************************************
19
20#region [ TVA Open Source Agreement ]
21/*
22
23 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
24 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
25 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
26 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
27 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
28 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
29 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
30
31 Original Software Designation: openPDC
32 Original Software Title: The GSF Open Source Phasor Data Concentrator
33 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
34 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
35
36 1. DEFINITIONS
37
38 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
39 that makes a Modification.
40
41 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
42 the use or sale of its Modification alone or when combined with the Subject Software.
43
44 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
45 image, or any other device.
46
47 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
48 another.
49
50 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
51 software separate from the Subject Software that is not governed by the terms of this Agreement.
52
53 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
54 structure of either the Original Software or Subject Software, and includes derivative works, as that
55 term is defined in the Copyright Statute, 17 USC � 101. However, the act of including Subject Software
56 as part of a Larger Work does not in and of itself constitute a Modification.
57
58 G. "Original Software" means the computer software first released under this Agreement by Government
59 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
60
61 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
62 Contributors.
63
64 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
65
66 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
67
68 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
69
70 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
71
72 M. "Use" means the application or employment of the Subject Software for any purpose.
73
74 2. GRANT OF RIGHTS
75
76 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
77 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
78 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
79 the Subject Software:
80
81 1. Use
82
83 2. Distribution
84
85 3. Reproduction
86
87 4. Modification
88
89 5. Redistribution
90
91 6. Display
92
93 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
94 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
95 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
96 pertaining to the Subject Software:
97
98 1. Use
99
100 2. Distribution
101
102 3. Reproduction
103
104 4. Sale
105
106 5. Offer for Sale
107
108 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
109 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
110 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
111 any other combinations that include a Modification.
112
113 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
114 Such sublicense must be under the same terms and conditions of this Agreement.
115
116 3. OBLIGATIONS OF RECIPIENT
117
118 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
119 additions covered under paragraph 3H.
120
121 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
122 must be included with each copy of the Subject Software; and
123
124 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
125 Recipient must also make the source code freely available, and must provide with each copy of the
126 Subject Software information on how to obtain the source code in a reasonable manner on or through a
127 medium customarily used for software exchange.
128
129 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
130 Software:
131
132 No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
133
134 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
135 must identify itself as the originator of its Modification in a manner that reasonably allows
136 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
137 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
138 made and the date of the alterations, identifies Contributor as originator of the alterations, and
139 consents to characterization of the alterations as a Modification, for example, by including a
140 statement that the Modification is derived, directly or indirectly, from Original Software provided by
141 Government Agency. Once consent is granted, it may not thereafter be revoked.
142
143 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
144 been added to the Subject Software, a Recipient may not remove it without the express permission of
145 the Contributor who added the notice.
146
147 E. A Recipient may not make any representation in the Subject Software or in any promotional,
148 advertising or other material that may be construed as an endorsement by Government Agency or by any
149 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
150 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
151
152 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
153 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
154 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
155 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
156 requested that the Recipient inform Government Agency at the web site provided above how to access the
157 Modification.
158
159 G. Each Contributor represents that that its Modification does not violate any existing agreements,
160 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
161 conveyed by this Agreement.
162
163 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
164 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
165 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
166 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
167 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
168 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
169 indemnity and/or liability offered by such Recipient.
170
171 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
172 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
173 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
174 is subject to this Agreement.
175
176 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
177 any goods or technical data from the United States may require some form of export license from the
178 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
179 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
180 required, it shall be issued. Nothing granted herein provides any such export license.
181
182 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
183
184 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
185 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
186 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
187 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
188 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
189 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
190 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
191 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
192 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
193 "AS IS."
194
195 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
196 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
197 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
198 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
199 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
200 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
201 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
202 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
203 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
204 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
205
206 5. GENERAL TERMS
207
208 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
209 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
210 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
211 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
212 Software properly granted by the breaching Recipient shall survive any such termination of this
213 Agreement.
214
215 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
216 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
217
218 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
219 including, but not limited to, determining the validity of this Agreement, the meaning of its
220 provisions and the rights, obligations and remedies of the parties.
221
222 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
223 parties relating to release of the Subject Software and may not be superseded, modified or amended
224 except by further written agreement duly executed by the parties.
225
226 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
227 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
228 Recipient hereby agrees to all terms and conditions herein.
229
230 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
231 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
232
233*/
234#endregion
235
236using System;
237using System.Collections.Generic;
238using System.Text;
239using System.Threading;
240
241namespace GSF.Threading
242{
243 /// <summary>
244 /// Maintains a reference to all managed threads
245 /// </summary>
246 public static class ManagedThreads
247 {
248 private static LinkedList<ManagedThread> s_queuedThreads;
249 private static LinkedList<ManagedThread> s_activeThreads;
250
251 static ManagedThreads()
252 {
253 s_queuedThreads = new LinkedList<ManagedThread>();
254 s_activeThreads = new LinkedList<ManagedThread>();
255 }
256
257 /// <summary>
258 /// Add an item to the active thread list
259 /// </summary>
260 /// <remarks>
261 /// Typically only used by standard threads when user calls "Start"
262 /// </remarks>
263 internal static void Add(ManagedThread item)
264 {
265 // Standard threads are simply added to the active thread list when started
266 lock (s_queuedThreads)
267 {
268 item.Status = ThreadStatus.Started;
269 s_activeThreads.AddLast(item);
270 }
271 }
272
273 /// <summary>
274 /// Remove completed thread from active thread list
275 /// </summary>
276 internal static void Remove(ManagedThread item)
277 {
278 lock (s_queuedThreads)
279 {
280 s_activeThreads.Remove(item);
281 }
282 }
283
284 /// <summary>
285 /// Queue thread for processing
286 /// </summary>
287 /// <remarks>
288 /// Typically only used by queued threads to add work items to the queue
289 /// </remarks>
290 internal static void Queue(ManagedThread item)
291 {
292 lock (s_queuedThreads)
293 {
294 s_queuedThreads.AddLast(item);
295 }
296 }
297
298 /// <summary>
299 /// Removes first item from the queue and transfers the item to the active thread list
300 /// </summary>
301 /// <returns>Next item to be processed</returns>
302 internal static ManagedThread Pop()
303 {
304 ManagedThread item = null;
305
306 // Transfer next queued thread to the active thread list
307 lock (s_queuedThreads)
308 {
309 if (s_queuedThreads.Count > 0)
310 {
311 item = s_queuedThreads.First.Value;
312 s_queuedThreads.RemoveFirst();
313 }
314
315 if ((object)item != null)
316 {
317 // Capture current thread (this is owned by .NET ThreadPool)
318 item.Thread = Thread.CurrentThread;
319 item.Status = ThreadStatus.Started;
320 s_activeThreads.AddLast(item);
321 }
322 }
323
324 return item;
325 }
326
327 /// <summary>
328 /// Returns a descriptive status of all queued and active mananged threads
329 /// </summary>
330 public static string ActiveThreadStatus
331 {
332 get
333 {
334 System.Text.StringBuilder status = new StringBuilder();
335 ManagedThread[] items = QueuedThreads;
336 int index = 0;
337
338 // Managed Thread Count: 1
339 //
340 // Thread 1 - Completed in 25 seconds
341 // Type: Standard Thread
342 // Name: TVASPDC.Service.CalculatedMeasurementInitialization.Initialize()
343
344 status.AppendFormat("Managed Thread Count: {0}{1}", items.Length, Environment.NewLine);
345 status.AppendLine();
346
347 foreach (ManagedThread item in items)
348 {
349 index++;
350 status.AppendFormat("Thread {0} - {1}{2}", index, ThreadStatusText(item), Environment.NewLine);
351 status.AppendFormat(" Type: {0}{1}", Enum.GetName(typeof(ThreadType), item.Type), Environment.NewLine);
352 status.AppendFormat(" Name: {0}{1}", item.Name, Environment.NewLine);
353 status.AppendLine();
354 }
355
356 return status.ToString();
357 }
358 }
359
360 private static string ThreadStatusText(ManagedThread item)
361 {
362 string runtime = item.RunTime.ToString();
363
364 switch (item.Status)
365 {
366 case ThreadStatus.Unstarted:
367 return "Not Started";
368 case ThreadStatus.Queued:
369 return "Queued";
370 case ThreadStatus.Executing:
371 return "Executing for " + runtime;
372 case ThreadStatus.Completed:
373 return "Completed in " + runtime;
374 case ThreadStatus.Aborted:
375 return "Aborted, ran for " + runtime;
376 default:
377 return "Status Unknown";
378 }
379 }
380
381 /// <summary>
382 /// Returns a copy of the currently queued and active threads
383 /// </summary>
384 public static ManagedThread[] QueuedThreads
385 {
386 get
387 {
388 List<ManagedThread> threads = new List<ManagedThread>();
389
390 lock (s_queuedThreads)
391 {
392 threads.AddRange(s_queuedThreads);
393 threads.AddRange(s_activeThreads);
394 }
395
396 return threads.ToArray();
397 }
398 }
399
400 /// <summary>
401 /// Removes a queued thread from thread pool if still queued, if allowAbort is True
402 /// aborts the thread if executing (standard or queued)
403 /// </summary>
404 /// <param name="item">Thread to cancel</param>
405 /// <param name="allowAbort">Set to True to abort thread if executing</param>
406 /// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted.</param>
407 public static void Cancel(ManagedThread item, bool allowAbort, object stateInfo)
408 {
409 if ((object)item == null)
410 throw new ArgumentNullException("item");
411
412 LinkedListNode<ManagedThread> node;
413
414 lock (s_queuedThreads)
415 {
416 // Change thread status to aborted
417 item.Status = ThreadStatus.Aborted;
418
419 // See if item is still queued for execution in thread pool
420 node = s_queuedThreads.Find(item);
421
422 // Handle abort or dequeue
423 if ((object)node == null)
424 {
425 if (allowAbort)
426 {
427 // Started items may be aborted, even if running in thread pool
428 if ((object)stateInfo == null)
429 item.Thread.Abort();
430 else
431 item.Thread.Abort(stateInfo);
432 }
433 }
434 else
435 {
436 // Remove item from queue if queued thread has yet to start
437 s_queuedThreads.Remove(node);
438 }
439 }
440 }
441 }
442}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t