-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCSharp.cs
More file actions
850 lines (808 loc) · 38.4 KB
/
CSharp.cs
File metadata and controls
850 lines (808 loc) · 38.4 KB
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
using System.Diagnostics;
using System.Reflection;
namespace BytecodeApi;
/// <summary>
/// Provides <see langword="static" /> methods and properties serving as a general object manipulation helper class.
/// </summary>
public static class CSharp
{
/// <summary>
/// Returns the converted version of <paramref name="obj" />, if it is of the specified type; otherwise, returns <see langword="default" />(<typeparamref name="T" />).
/// </summary>
/// <typeparam name="T">The type to which to convert <paramref name="obj" /> to.</typeparam>
/// <param name="obj">The <see cref="object" /> to be converted.</param>
/// <returns>
/// The converted version of <paramref name="obj" />, if it is of the specified type; otherwise, returns <see langword="default" />(<typeparamref name="T" />).
/// </returns>
public static T? CastOrDefault<T>(object? obj)
{
return obj is T castedObject ? castedObject : default;
}
/// <summary>
/// Performs an <see cref="Action" /> and disposes <paramref name="obj" />, if <paramref name="obj" /> is an <see cref="IDisposable" />. This is useful if the given <see cref="object" /> only indirectly inherits <see cref="IDisposable" /> and therefore the <see langword="using" /> keyword cannot be used.
/// </summary>
/// <param name="obj">The <see cref="object" /> to be disposed. If <paramref name="obj" /> is not an <see cref="IDisposable" />, it will not be disposed.</param>
/// <param name="action">The <see cref="Action" /> to be performed before the <see cref="IDisposable.Dispose" /> method is called. This is equivalent to the body of the <see langword="using" /> statement.</param>
public static void Using(object? obj, Action action)
{
Check.ArgumentNull(action);
try
{
action();
}
finally
{
(obj as IDisposable)?.Dispose();
}
}
/// <summary>
/// Performs an <see cref="Action" /> and disposes all objects in the specified array that are <see cref="IDisposable" />.
/// </summary>
/// <param name="objects">An array of objects to be disposed.</param>
/// <param name="action">The <see cref="Action" /> to be performed before the <see cref="IDisposable.Dispose" /> method is called. This is equivalent to the body of the <see langword="using" /> statement.</param>
public static void Using(object?[] objects, Action action)
{
Check.ArgumentNull(objects);
Check.ArgumentNull(action);
try
{
action();
}
finally
{
foreach (object? obj in objects)
{
(obj as IDisposable)?.Dispose();
}
}
}
/// <summary>
/// Copies the contents of properties and fields of an <see cref="object" /> to another <see cref="object" /> of a different <see cref="Type" /> by comparing property and field names. A new instance of <typeparamref name="TDest" /> is created.
/// <para>Values are only copied, if the property or field is of equivalent type. This includes conversion between mixed <see cref="Nullable" /> values (e.g. <see cref="int" /> and <see cref="int" />?), and between <see cref="Enum" /> and numeric values. Differing types are attempted to convert (e.g. <see cref="int" /> and <see cref="long" />). If conversion fails, the default value of the destination type is used.</para>
/// </summary>
/// <typeparam name="TDest">The type of the <see cref="object" /> to copy the contents to.</typeparam>
/// <param name="obj">The <see cref="object" /> to copy the contents from.</param>
/// <returns>
/// The new instance of <typeparamref name="TDest" /> this method creates, with properties and fields copied from <paramref name="obj" />.
/// </returns>
public static TDest ConvertObject<TDest>(object obj) where TDest : class
{
return ConvertObject<TDest>(obj, ConvertObjectOptions.None);
}
/// <summary>
/// Copies the contents of properties and fields of an <see cref="object" /> to another <see cref="object" /> of a different <see cref="Type" /> by comparing property and field names. A new instance of <typeparamref name="TDest" /> is created.
/// <para>Values are only copied, if the property or field is of equivalent type. This includes conversion between mixed <see cref="Nullable" /> values (e.g. <see cref="int" /> and <see cref="int" />?), and between <see cref="Enum" /> and numeric values. Differing types are attempted to convert (e.g. <see cref="int" /> and <see cref="long" />). If conversion fails, the default value of the destination type is used.</para>
/// </summary>
/// <typeparam name="TDest">The type of the <see cref="object" /> to copy the contents to.</typeparam>
/// <param name="obj">The <see cref="object" /> to copy the contents from.</param>
/// <param name="flags">The <see cref="ConvertObjectOptions" /> flags that specify comparison and copy behavior.</param>
/// <returns>
/// The new instance of <typeparamref name="TDest" /> this method creates, with properties and fields copied from <paramref name="obj" />.
/// </returns>
public static TDest ConvertObject<TDest>(object obj, ConvertObjectOptions flags) where TDest : class
{
Check.ArgumentNull(obj);
TDest dest = Activator.CreateInstance<TDest>();
ConvertObject(obj, dest, flags);
return dest;
}
/// <summary>
/// Copies the contents of properties and fields of an <see cref="object" /> to another <see cref="object" /> of a different <see cref="Type" /> by comparing property and field names.
/// <para>Values are only copied, if the property or field is of equivalent type. This includes conversion between mixed <see cref="Nullable" /> values (e.g. <see cref="int" /> and <see cref="int" />?), and between <see cref="Enum" /> and numeric values. Differing types are attempted to convert (e.g. <see cref="int" /> and <see cref="long" />). If conversion fails, the default value of the destination type is used.</para>
/// </summary>
/// <typeparam name="TDest">The type of the <see cref="object" /> to copy the contents to.</typeparam>
/// <param name="obj">The <see cref="object" /> to copy the contents from.</param>
/// <param name="dest">The <see cref="object" /> to copy the contents to.</param>
public static void ConvertObject<TDest>(object obj, TDest dest) where TDest : class
{
ConvertObject(obj, dest, ConvertObjectOptions.None);
}
/// <summary>
/// Copies the contents of properties and fields of an <see cref="object" /> to another <see cref="object" /> of a different <see cref="Type" /> by comparing property and field names.
/// <para>Values are only copied, if the property or field is of equivalent type. This includes conversion between mixed <see cref="Nullable" /> values (e.g. <see cref="int" /> and <see cref="int" />?), and between <see cref="Enum" /> and numeric values. Differing types are attempted to convert (e.g. <see cref="int" /> and <see cref="long" />). If conversion fails, the default value of the destination type is used.</para>
/// </summary>
/// <typeparam name="TDest">The type of the <see cref="object" /> to copy the contents to.</typeparam>
/// <param name="obj">The <see cref="object" /> to copy the contents from.</param>
/// <param name="dest">The <see cref="object" /> to copy the contents to.</param>
/// <param name="flags">The <see cref="ConvertObjectOptions" /> flags that specify comparison and copy behavior.</param>
public static void ConvertObject<TDest>(object obj, TDest dest, ConvertObjectOptions flags) where TDest : class
{
Check.ArgumentNull(obj);
Check.ArgumentNull(dest);
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (flags.HasFlag(ConvertObjectOptions.IgnoreCase)) bindingFlags |= BindingFlags.IgnoreCase;
if (flags.HasFlag(ConvertObjectOptions.NonPublic)) bindingFlags |= BindingFlags.NonPublic;
if (flags.HasFlag(ConvertObjectOptions.Static)) bindingFlags |= BindingFlags.Static;
if (!flags.HasFlag(ConvertObjectOptions.IgnoreProperties))
{
foreach (PropertyInfo sourceProperty in obj.GetType().GetProperties(bindingFlags))
{
if (dest.GetType().GetProperty(sourceProperty.Name, bindingFlags) is PropertyInfo destProperty && destProperty.SetMethod != null)
{
Process
(
sourceProperty.PropertyType,
destProperty.PropertyType,
() => sourceProperty.GetValue(obj),
value => destProperty.SetValue(dest, value)
);
}
if (flags.HasFlag(ConvertObjectOptions.PropertiesToFields) && dest.GetType().GetField(sourceProperty.Name, bindingFlags) is FieldInfo destField)
{
Process
(
sourceProperty.PropertyType,
destField.FieldType,
() => sourceProperty.GetValue(obj),
value => destField.SetValue(dest, value)
);
}
}
}
if (!flags.HasFlag(ConvertObjectOptions.IgnoreFields))
{
foreach (FieldInfo sourceField in obj.GetType().GetFields(bindingFlags))
{
if (dest.GetType().GetField(sourceField.Name, bindingFlags) is FieldInfo destField)
{
Process
(
sourceField.FieldType,
destField.FieldType,
() => sourceField.GetValue(obj),
value => destField.SetValue(dest, value)
);
}
if (flags.HasFlag(ConvertObjectOptions.FieldsToProperties) && dest.GetType().GetProperty(sourceField.Name, bindingFlags) is PropertyInfo destProperty && destProperty.SetMethod != null)
{
Process
(
sourceField.FieldType,
destProperty.PropertyType,
() => sourceField.GetValue(obj),
value => destProperty.SetValue(dest, value)
);
}
}
}
static void Process(Type sourceType, Type destType, Func<object?> getValue, Action<object?> setValue)
{
GetEffectiveType(ref sourceType);
GetEffectiveType(ref destType);
if (sourceType == destType)
{
setValue(getValue());
return;
}
else
{
try
{
setValue(Convert.ChangeType(getValue(), destType));
return;
}
catch
{
}
}
setValue(null);
}
static void GetEffectiveType(ref Type type)
{
if (Nullable.GetUnderlyingType(type) is Type nullable)
{
type = nullable;
}
if (type.IsEnum)
{
type = type.GetEnumUnderlyingType();
}
}
}
/// <summary>
/// Invokes an <see cref="Action" /> and handles any exception. Returns <see langword="true" /> on successful execution and <see langword="false" />, if an exception was thrown.
/// </summary>
/// <param name="action">The <see cref="Action" /> to be invoked.</param>
/// <returns>
/// <see langword="true" />, on successful execution and
/// <see langword="false" />, if an exception was thrown.
/// </returns>
public static bool Try(Action action)
{
Check.ArgumentNull(action);
try
{
action();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Schedules a <see cref="Task" /> and handles any exception. Returns <see langword="true" /> on successful execution and <see langword="false" />, if an exception was thrown.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <returns>
/// <see langword="true" />, on successful execution and
/// <see langword="false" />, if an exception was thrown.
/// </returns>
public static async Task<bool> Try(Func<Task> task)
{
Check.ArgumentNull(task);
try
{
await task();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Schedules a <see cref="Task" /> and handles any exception. Returns <see langword="true" /> on successful execution and <see langword="false" />, if an exception was thrown.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <returns>
/// <see langword="true" />, on successful execution and
/// <see langword="false" />, if an exception was thrown.
/// </returns>
public static async Task<bool> Try(Task task)
{
Check.ArgumentNull(task);
try
{
await task;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Invokes a <see cref="Func{TResult}" /> and handles any exception. Returns the result of <paramref name="func" /> on successful execution and <see langword="default" />(<typeparamref name="T" />) if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func" />.</typeparam>
/// <param name="func">The <see cref="Func{TResult}" /> to be invoked.</param>
/// <returns>
/// The result of <paramref name="func" />, on successful execution and
/// <see langword="default" />(<typeparamref name="T" />), if an exception was thrown.
/// </returns>
public static T? Try<T>(Func<T> func)
{
return Try(func, default(T));
}
/// <summary>
/// Invokes a <see cref="Func{TResult}" /> and handles any exception. Returns the result of <paramref name="func" /> on successful execution and <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func" />.</typeparam>
/// <param name="func">The <see cref="Func{TResult}" /> to be invoked.</param>
/// <param name="defaultValue">The default value that is returned if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="func" />, on successful execution and
/// <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static T Try<T>(Func<T> func, T defaultValue)
{
Check.ArgumentNull(func);
try
{
return func();
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Invokes a <see cref="Func{TResult}" /> and handles any exception. Returns the result of <paramref name="func" /> on successful execution and invokes and returns <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func" />.</typeparam>
/// <param name="func">The <see cref="Func{TResult}" /> to be invoked.</param>
/// <param name="defaultValue">The <see cref="Func{TResult}" /> that is invoked and whose result is returned, if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="func" />, on successful execution and
/// The result of <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static T Try<T>(Func<T> func, Func<T> defaultValue)
{
Check.ArgumentNull(func);
Check.ArgumentNull(defaultValue);
try
{
return func();
}
catch
{
return defaultValue();
}
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and <see langword="default" />(<typeparamref name="T" />) if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// <see langword="default" />(<typeparamref name="T" />), if an exception was thrown.
/// </returns>
public static Task<T?> Try<T>(Func<Task<T?>> task)
{
return Try(task, default(T));
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="defaultValue">The default value that is returned if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static async Task<T> Try<T>(Func<Task<T>> task, T defaultValue)
{
Check.ArgumentNull(task);
try
{
return await task();
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and invokes and returns <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="defaultValue">The <see cref="Func{TResult}" /> that is invoked and whose result is returned, if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// The result of <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static async Task<T> Try<T>(Func<Task<T>> task, Func<T> defaultValue)
{
Check.ArgumentNull(task);
Check.ArgumentNull(defaultValue);
try
{
return await task();
}
catch
{
return defaultValue();
}
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and <see langword="default" />(<typeparamref name="T" />) if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// <see langword="default" />(<typeparamref name="T" />), if an exception was thrown.
/// </returns>
public static Task<T?> Try<T>(Task<T?> task)
{
return Try(task, default(T));
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="defaultValue">The default value that is returned if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static async Task<T> Try<T>(Task<T> task, T defaultValue)
{
Check.ArgumentNull(task);
try
{
return await task;
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> and handles any exception. Returns the result of <paramref name="task" /> on successful execution and invokes and returns <paramref name="defaultValue" />, if an exception was thrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="defaultValue">The <see cref="Func{TResult}" /> that is invoked and whose result is returned, if an exception was thrown.</param>
/// <returns>
/// The result of <paramref name="task" />, on successful execution and
/// The result of <paramref name="defaultValue" />, if an exception was thrown.
/// </returns>
public static async Task<T> Try<T>(Task<T> task, Func<T> defaultValue)
{
Check.ArgumentNull(task);
Check.ArgumentNull(defaultValue);
try
{
return await task;
}
catch
{
return defaultValue();
}
}
/// <summary>
/// Attempts to invoke an <see cref="Action" /> up to a defined number of times until <paramref name="action" /> successfully returned without throwing an exception. If <paramref name="action" /> throws an exception on the last time, the exception is rethrown.
/// </summary>
/// <param name="action">The <see cref="Action" /> to be invoked.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="action" /> is attempted before the final exception is rethrown.</param>
public static void Retry(Action action, int attempts)
{
Retry(action, attempts, TimeSpan.Zero);
}
/// <summary>
/// Attempts to invoke an <see cref="Action" /> up to a defined number of times until <paramref name="action" /> successfully returned without throwing an exception. If <paramref name="action" /> throws an exception on the last time, the exception is rethrown. Between each call of <paramref name="action" /> that throws an exception, a delay is waited.
/// </summary>
/// <param name="action">The <see cref="Action" /> to be invoked.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="action" /> is attempted before the final exception is rethrown.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="action" /> that throws an exception.</param>
public static void Retry(Action action, int attempts, TimeSpan delay)
{
Check.ArgumentNull(action);
Check.ArgumentOutOfRangeEx.Greater0(attempts);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (; ; attempts--)
{
try
{
action();
return;
}
catch when (attempts <= 1)
{
throw;
}
catch
{
Thread.Sleep(delay);
}
}
}
/// <summary>
/// Attempts to schedule a <see cref="Task" /> up to a defined number of times until <paramref name="task" /> successfully returned without throwing an exception. If <paramref name="task" /> throws an exception on the last time, the exception is rethrown.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="task" /> is attempted before the final exception is rethrown.</param>
public static Task Retry(Func<Task> task, int attempts)
{
return Retry(task, attempts, TimeSpan.Zero);
}
/// <summary>
/// Attempts to schedule a <see cref="Task" /> up to a defined number of times until <paramref name="task" /> successfully returned without throwing an exception. If <paramref name="task" /> throws an exception on the last time, the exception is rethrown. Between each call of <paramref name="task" /> that throws an exception, a delay is waited.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="task" /> is attempted before the final exception is rethrown.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="task" /> that throws an exception.</param>
public static async Task Retry(Func<Task> task, int attempts, TimeSpan delay)
{
Check.ArgumentNull(task);
Check.ArgumentOutOfRangeEx.Greater0(attempts);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (; ; attempts--)
{
try
{
await task();
return;
}
catch when (attempts <= 1)
{
throw;
}
catch
{
await Task.Delay(delay);
}
}
}
/// <summary>
/// Attempts to invoke a <see cref="Func{TResult}" /> up to a defined number of times until <paramref name="func" /> successfully returns a value without throwing an exception. If <paramref name="func" /> throws an exception on the last time, the exception is rethrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func" />.</typeparam>
/// <param name="func">The <see cref="Func{TResult}" /> to be invoked.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="func" /> is attempted before the final exception is rethrown.</param>
/// <returns>
/// The result of <paramref name="func" />, if <paramref name="func" /> successfully returned a value in the given number of attempts without throwing an exception;
/// otherwise, rethrows the exception.
/// </returns>
public static T Retry<T>(Func<T> func, int attempts)
{
return Retry(func, attempts, TimeSpan.Zero);
}
/// <summary>
/// Attempts to invoke a <see cref="Func{TResult}" /> up to a defined number of times until <paramref name="func" /> successfully returns a value without throwing an exception. If <paramref name="func" /> throws an exception on the last time, the exception is rethrown. Between each call of <paramref name="func" /> that throws an exception, a delay is waited.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func" />.</typeparam>
/// <param name="func">The <see cref="Func{TResult}" /> to be invoked.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="func" /> is attempted before the final exception is rethrown.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="func" /> that throws an exception.</param>
/// <returns>
/// The result of <paramref name="func" />, if <paramref name="func" /> successfully returned a value in the given number of attempts without throwing an exception;
/// otherwise, rethrows the exception.
/// </returns>
public static T Retry<T>(Func<T> func, int attempts, TimeSpan delay)
{
Check.ArgumentNull(func);
Check.ArgumentOutOfRangeEx.Greater0(attempts);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (; ; attempts--)
{
try
{
return func();
}
catch when (attempts <= 1)
{
throw;
}
catch
{
Thread.Sleep(delay);
}
}
}
/// <summary>
/// Attempts to schedule a <see cref="Task{TResult}" /> up to a defined number of times until <paramref name="task" /> successfully returns a value without throwing an exception. If <paramref name="task" /> throws an exception on the last time, the exception is rethrown.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="task" /> is attempted before the final exception is rethrown.</param>
/// <returns>
/// The result of <paramref name="task" />, if <paramref name="task" /> successfully returned a value in the given number of attempts without throwing an exception;
/// otherwise, rethrows the exception.
/// </returns>
public static Task<T> Retry<T>(Func<Task<T>> task, int attempts)
{
return Retry(task, attempts, TimeSpan.Zero);
}
/// <summary>
/// Attempts to schedule a <see cref="Task{TResult}" /> up to a defined number of times until <paramref name="task" /> successfully returns a value without throwing an exception. If <paramref name="task" /> throws an exception on the last time, the exception is rethrown. Between each call of <paramref name="task" /> that throws an exception, a delay is waited.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="task" />.</typeparam>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="attempts">A <see cref="int" /> value indicating how many times <paramref name="task" /> is attempted before the final exception is rethrown.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="task" /> that throws an exception.</param>
/// <returns>
/// The result of <paramref name="task" />, if <paramref name="task" /> successfully returned a value in the given number of attempts without throwing an exception;
/// otherwise, rethrows the exception.
/// </returns>
public static async Task<T> Retry<T>(Func<Task<T>> task, int attempts, TimeSpan delay)
{
Check.ArgumentNull(task);
Check.ArgumentOutOfRangeEx.Greater0(attempts);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (; ; attempts--)
{
try
{
return await task();
}
catch when (attempts <= 1)
{
throw;
}
catch
{
await Task.Delay(delay);
}
}
}
/// <summary>
/// Invokes a <see cref="Func{TResult}" /> until the result of <paramref name="func" /> is <see langword="true" /> or <paramref name="timeout" /> has been reached. If <paramref name="func" /> does not return <see langword="true" /> in this timeframe, <see langword="false" /> is returned, otherwise, <see langword="true" />.
/// </summary>
/// <param name="func">The <see cref="Func{TResult}" /> to be tested.</param>
/// <param name="timeout">A <see cref="TimeSpan" /> value representing the total time for <paramref name="func" /> to be tested.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="func" /> returned <see langword="true" /> in the specified <paramref name="timeout" />;
/// otherwise, <see langword="false" />.
/// </returns>
public static bool Timeout(Func<bool> func, TimeSpan timeout)
{
return Timeout(func, timeout, TimeSpan.Zero);
}
/// <summary>
/// Invokes a <see cref="Func{TResult}" /> until the result of <paramref name="func" /> is <see langword="true" /> or <paramref name="timeout" /> has been reached. If <paramref name="func" /> does not return <see langword="true" /> in this timeframe, <see langword="false" /> is returned, otherwise, <see langword="true" />. Between each call of <paramref name="func" /> that returns <see langword="false" />, a delay is waited.
/// </summary>
/// <param name="func">The <see cref="Func{TResult}" /> to be tested.</param>
/// <param name="timeout">A <see cref="TimeSpan" /> value representing the total time for <paramref name="func" /> to be tested.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="func" /> that returns <see langword="false" />.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="func" /> returned <see langword="true" /> in the specified <paramref name="timeout" />;
/// otherwise, <see langword="false" />.
/// </returns>
public static bool Timeout(Func<bool> func, TimeSpan timeout, TimeSpan delay)
{
Check.ArgumentNull(func);
Check.ArgumentOutOfRangeEx.GreaterEqual0(timeout);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (Stopwatch stopwatch = Stopwatch.StartNew(); stopwatch.Elapsed < timeout; Thread.Sleep(delay))
{
if (func())
{
return true;
}
}
return false;
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> until the result of <paramref name="task" /> is <see langword="true" /> or <paramref name="timeout" /> has been reached. If <paramref name="task" /> does not return <see langword="true" /> in this timeframe, <see langword="false" /> is returned, otherwise, <see langword="true" />.
/// </summary>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="timeout">A <see cref="TimeSpan" /> value representing the total time for <paramref name="task" /> to be tested.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="task" /> returned <see langword="true" /> in the specified <paramref name="timeout" />;
/// otherwise, <see langword="false" />.
/// </returns>
public static Task<bool> Timeout(Func<Task<bool>> task, TimeSpan timeout)
{
return Timeout(task, timeout, TimeSpan.Zero);
}
/// <summary>
/// Schedules a <see cref="Task{TResult}" /> until the result of <paramref name="task" /> is <see langword="true" /> or <paramref name="timeout" /> has been reached. If <paramref name="task" /> does not return <see langword="true" /> in this timeframe, <see langword="false" /> is returned, otherwise, <see langword="true" />. Between each call of <paramref name="task" /> that returns <see langword="false" />, a delay is waited.
/// </summary>
/// <param name="task">The <see cref="Task{TResult}" /> to be scheduled.</param>
/// <param name="timeout">A <see cref="TimeSpan" /> value representing the total time for <paramref name="task" /> to be tested.</param>
/// <param name="delay">A <see cref="TimeSpan" /> value representing the wait period between each call of <paramref name="task" /> that returns <see langword="false" />.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="task" /> returned <see langword="true" /> in the specified <paramref name="timeout" />;
/// otherwise, <see langword="false" />.
/// </returns>
public static async Task<bool> Timeout(Func<Task<bool>> task, TimeSpan timeout, TimeSpan delay)
{
Check.ArgumentNull(task);
Check.ArgumentOutOfRangeEx.GreaterEqual0(timeout);
Check.ArgumentOutOfRangeEx.GreaterEqual0(delay);
for (Stopwatch stopwatch = Stopwatch.StartNew(); stopwatch.Elapsed < timeout; await Task.Delay(delay))
{
if (await task())
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <see langword="true" />, if <paramref name="obj" /> is an <see cref="object" /> of the specified <see cref="Type" />. If <paramref name="obj" /> is not of the specified <see cref="Type" />, or <paramref name="obj" /> is of a <see cref="Type" /> that inherits <paramref name="type" />, <see langword="false" /> is returned.
/// </summary>
/// <param name="obj">The <see cref="object" /> to check.</param>
/// <param name="type">The <see cref="Type" /> to compare to the type of <paramref name="obj" />.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="obj" /> is an <see cref="object" /> of the specified <see cref="Type" />;
/// <see langword="false" />, If <paramref name="obj" /> is not of the specified <see cref="Type" />, or <paramref name="obj" /> is of a <see cref="Type" /> that inherits <paramref name="type" />.
/// </returns>
public static bool IsType([NotNullWhen(true)] object? obj, Type type)
{
Check.ArgumentNull(type);
return obj?.GetType() == type;
}
/// <summary>
/// Returns <see langword="true" />, if <paramref name="obj" /> is an <see cref="object" /> of the specified type. If <paramref name="obj" /> is not of the specified type, or <paramref name="obj" /> is of a type that inherits <typeparamref name="T" />, <see langword="false" /> is returned.
/// </summary>
/// <typeparam name="T">The type to compare to the type of <paramref name="obj" />.</typeparam>
/// <param name="obj">The <see cref="object" /> to check.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="obj" /> is an <see cref="object" /> of the specified type;
/// <see langword="false" />, If <paramref name="obj" /> is not of the specified type, or <paramref name="obj" /> is of a type that inherits <typeparamref name="T" />.
/// </returns>
public static bool IsType<T>([NotNullWhen(true)] object? obj)
{
return obj?.GetType() == typeof(T);
}
/// <summary>
/// Returns <see langword="true" />, if <paramref name="objA" /> and <paramref name="objB" /> are of the same <see cref="Type" />, of if both objects are <see langword="null" />.
/// </summary>
/// <param name="objA">The first <see cref="object" /> to compare.</param>
/// <param name="objB">The second <see cref="object" /> to compare.</param>
/// <returns>
/// <see langword="true" />, if <paramref name="objA" /> and <paramref name="objB" /> are of the same <see cref="Type" />, of if both objects are <see langword="null" />;
/// otherwise, <see langword="false" />.
/// </returns>
public static bool TypeEquals(object? objA, object? objB)
{
return objA?.GetType() == objB?.GetType();
}
/// <summary>
/// Invokes an <see cref="Action" /> and measures the time until <paramref name="action" /> returned.
/// </summary>
/// <param name="action">The <see cref="Action" /> to be invoked.</param>
/// <returns>
/// A <see cref="TimeSpan" /> value with the time <paramref name="action" /> took to return.
/// </returns>
public static TimeSpan MeasureTime(Action action)
{
Check.ArgumentNull(action);
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
/// <summary>
/// Schedules a <see cref="Task" /> and measures the time until <paramref name="task" /> finished.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <returns>
/// A <see cref="TimeSpan" /> value with the time <paramref name="task" /> took to finish.
/// </returns>
public static async Task<TimeSpan> MeasureTime(Func<Task> task)
{
Check.ArgumentNull(task);
Stopwatch stopwatch = Stopwatch.StartNew();
await task();
stopwatch.Stop();
return stopwatch.Elapsed;
}
/// <summary>
/// Schedules a <see cref="Task" /> and measures the time until <paramref name="task" /> finished.
/// </summary>
/// <param name="task">The <see cref="Task" /> to be scheduled.</param>
/// <returns>
/// A <see cref="TimeSpan" /> value with the time <paramref name="task" /> took to finish.
/// </returns>
public static async Task<TimeSpan> MeasureTime(Task task)
{
Check.ArgumentNull(task);
Stopwatch stopwatch = Stopwatch.StartNew();
await task;
stopwatch.Stop();
return stopwatch.Elapsed;
}
/// <summary>
/// Runs the specified <see cref="Task" /> synchronously and waits for the task to finish.
/// </summary>
/// <param name="task">The task to run.</param>
public static void RunTask(Func<Task> task)
{
Task.Run(async () => await task()).Wait();
}
/// <summary>
/// Runs the specified <see cref="Task" /> synchronously and waits for the task to finish.
/// </summary>
/// <param name="task">The task to run.</param>
public static void RunTask(Task task)
{
Task.Run(async () => await task).Wait();
}
/// <summary>
/// Runs the specified <see cref="Task{TResult}" /> synchronously and waits for the task to finish.
/// </summary>
/// <typeparam name="T">The type of the <see cref="Task{TResult}" />.</typeparam>
/// <param name="task">The task to run.</param>
/// <returns>
/// The value that <paramref name="task" /> returned.
/// </returns>
public static T RunTask<T>(Func<Task<T>> task)
{
T result = default!;
Task.Run(async () => result = await task()).Wait();
return result;
}
/// <summary>
/// Runs the specified <see cref="Task{TResult}" /> synchronously and waits for the task to finish.
/// </summary>
/// <typeparam name="T">The type of the <see cref="Task{TResult}" />.</typeparam>
/// <param name="task">The task to run.</param>
/// <returns>
/// The value that <paramref name="task" /> returned.
/// </returns>
public static T RunTask<T>(Task<T> task)
{
T result = default!;
Task.Run(async () => result = await task).Wait();
return result;
}
}