-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
ThreadTests.cs
1302 lines (1148 loc) · 55.2 KB
/
ThreadTests.cs
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Threading.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Threading.Threads.Tests
{
public class DummyClass
{
public static string HostRunnerTest = RemoteExecutor.HostRunner;
}
public static class ThreadTests
{
private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds;
private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds;
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ConstructorTest()
{
const int SmallStackSizeBytes = 128 << 10; // 128 KB
const int LargeStackSizeBytes = 16 << 20; // 16 MB
int pageSizeBytes = Environment.SystemPageSize;
// Leave some buffer for other data structures that will take some of the allocated stack space
int stackSizeBufferBytes = pageSizeBytes * 16;
Action<Thread> startThreadAndJoin =
t =>
{
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
};
Action<int> verifyStackSize =
stackSizeBytes =>
{
// Try to stack-allocate an array to verify that close to the expected amount of stack space is actually
// available
int bufferSizeBytes = Math.Max(SmallStackSizeBytes / 4, stackSizeBytes - stackSizeBufferBytes);
unsafe
{
byte* buffer = stackalloc byte[bufferSizeBytes];
for (int i = 0; i < bufferSizeBytes; i += pageSizeBytes)
{
Volatile.Write(ref buffer[i], 0xff);
}
Volatile.Write(ref buffer[bufferSizeBytes - 1], 0xff);
}
};
startThreadAndJoin(new Thread(() => verifyStackSize(0)));
startThreadAndJoin(new Thread(() => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(() => verifyStackSize(SmallStackSizeBytes), SmallStackSizeBytes));
startThreadAndJoin(new Thread(() => verifyStackSize(LargeStackSizeBytes), LargeStackSizeBytes));
startThreadAndJoin(new Thread(state => verifyStackSize(0)));
startThreadAndJoin(new Thread(state => verifyStackSize(0), 0));
startThreadAndJoin(new Thread(state => verifyStackSize(SmallStackSizeBytes), SmallStackSizeBytes));
startThreadAndJoin(new Thread(state => verifyStackSize(LargeStackSizeBytes), LargeStackSizeBytes));
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null, 0));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null));
Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(() => { }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(state => { }, -1));
}
public static IEnumerable<object[]> ApartmentStateTest_MemberData()
{
yield return
new object[]
{
#pragma warning disable 618 // Obsolete members
new Func<Thread, ApartmentState>(t => t.ApartmentState),
#pragma warning restore 618 // Obsolete members
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
#pragma warning disable 618 // Obsolete members
t.ApartmentState = value;
#pragma warning restore 618 // Obsolete members
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
0
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
t.SetApartmentState(value);
return 0;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (InvalidOperationException)
{
return 2;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
1
};
yield return
new object[]
{
new Func<Thread, ApartmentState>(t => t.GetApartmentState()),
new Func<Thread, ApartmentState, int>(
(t, value) =>
{
try
{
return t.TrySetApartmentState(value) ? 0 : 2;
}
catch (ArgumentOutOfRangeException)
{
return 1;
}
catch (PlatformNotSupportedException)
{
return 3;
}
}),
2
};
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotMobile), nameof(PlatformDetection.HasHostExecutable))]
[InlineData("STAMain.exe", "GetApartmentStateTest")]
[InlineData("STAMain.exe", "SetApartmentStateTest")]
[InlineData("STAMain.exe", "WaitAllNotSupportedOnSta_Test0")]
[InlineData("STAMain.exe", "WaitAllNotSupportedOnSta_Test1")]
[InlineData("MTAMain.exe", "GetApartmentStateTest")]
[InlineData("MTAMain.exe", "SetApartmentStateTest")]
[InlineData("DefaultApartmentStateMain.exe", "GetApartmentStateTest")]
[InlineData("DefaultApartmentStateMain.exe", "SetApartmentStateTest")]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34543", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/86722", typeof(PlatformDetection), nameof(PlatformDetection.IsReadyToRunCompiled))]
public static void ApartmentState_AttributePresent(string appName, string testName)
{
var psi = new ProcessStartInfo();
psi.FileName = DummyClass.HostRunnerTest;
psi.Arguments = $"{appName} {testName}";
using (Process p = Process.Start(psi))
{
p.WaitForExit();
Assert.Equal(PlatformDetection.IsWindows ? 0 : 2, p.ExitCode);
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34543", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void ApartmentState_NoAttributePresent_DefaultState_Windows()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState());
AssertExtensions.ThrowsContains<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA), "MTA");
Thread.CurrentThread.SetApartmentState(ApartmentState.MTA);
}).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void ApartmentState_NoAttributePresent_DefaultState_Unix()
{
RemoteExecutor.Invoke(() =>
{
Assert.Equal(ApartmentState.Unknown, Thread.CurrentThread.GetApartmentState());
Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.MTA));
}).Dispose();
}
private static bool IsWindowsNanoServerAndRemoteExecutorSupported => PlatformDetection.IsWindowsNanoServer && RemoteExecutor.IsSupported;
// Thread is always initialized as MTA irrespective of the attribute present.
[ConditionalFact(nameof(IsWindowsNanoServerAndRemoteExecutorSupported))]
public static void ApartmentState_NoAttributePresent_DefaultState_Nano()
{
RemoteExecutor.Invoke(() =>
{
Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA));
Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState());
}).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void ApartmentState_NoAttributePresent_STA_Unix()
{
RemoteExecutor.Invoke(() =>
{
Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA));
}).Dispose();
}
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34543", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
public static void GetSetApartmentStateTest_ChangeAfterThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
Assert.Equal(1, setApartmentState(t, ApartmentState.STA - 1));
Assert.Equal(1, setApartmentState(t, ApartmentState.Unknown + 1));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.MTA));
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.STA)); // cannot be changed after thread is started
Assert.Equal(ApartmentState.MTA, getApartmentState(t));
});
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34543", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows
public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ApartmentState apartmentStateInThread = ApartmentState.Unknown;
Thread t = null;
t = new Thread(() => apartmentStateInThread = getApartmentState(t));
t.IsBackground = true;
Assert.Equal(0, setApartmentState(t, ApartmentState.STA));
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once
Assert.Equal(ApartmentState.STA, getApartmentState(t));
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.Equal(ApartmentState.STA, apartmentStateInThread);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindowsNanoServer))]
[MemberData(nameof(ApartmentStateTest_MemberData))]
public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows_Nano_Server(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
ApartmentState apartmentStateInThread = ApartmentState.Unknown;
Thread t = null;
t = new Thread(() => apartmentStateInThread = getApartmentState(t));
t.IsBackground = true;
Assert.Equal(0, setApartmentState(t, ApartmentState.STA));
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once
Assert.Equal(ApartmentState.STA, getApartmentState(t));
Exception ex = Assert.Throws<ThreadStartException>(() => t.Start()); // Windows Nano Server does not support starting threads in the STA.
Assert.IsType<PlatformNotSupportedException>(ex.InnerException);
}
[Theory]
[MemberData(nameof(ApartmentStateTest_MemberData))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior differs on Unix and Windows
public static void ApartmentStateTest_Unix(
Func<Thread, ApartmentState> getApartmentState,
Func<Thread, ApartmentState, int> setApartmentState,
int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */)
{
var t = new Thread(() => { });
Assert.Equal(ApartmentState.Unknown, getApartmentState(t));
Assert.Equal(0, setApartmentState(t, ApartmentState.Unknown));
int expectedFailure;
switch (setType)
{
case 0:
expectedFailure = 0; // ApartmentState setter - no exception, but value does not change
break;
case 1:
expectedFailure = 3; // SetApartmentState - InvalidOperationException
break;
default:
expectedFailure = 2; // TrySetApartmentState - returns false
break;
}
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.STA));
Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.MTA));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentCultureTest_DifferentThread()
{
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
CultureInfo uiCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ExceptionDispatchInfo exceptionFromThread = null;
var t = new Thread(() =>
{
try
{
Assert.Same(culture, Thread.CurrentThread.CurrentCulture);
Assert.Same(uiCulture, Thread.CurrentThread.CurrentUICulture);
}
catch (Exception e)
{
exceptionFromThread = ExceptionDispatchInfo.Capture(e);
}
});
// We allow setting thread culture of unstarted threads to ease .NET Framework migration. It is pattern used
// in real world .NET Framework apps.
t.CurrentCulture = culture;
t.CurrentUICulture = uiCulture;
// Cannot access culture properties on a thread object from a different thread
Assert.Throws<InvalidOperationException>(() => t.CurrentCulture);
Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture);
t.Start();
// Cannot access culture properties on a thread object from a different thread once the thread is started
// .NET Framework allowed this, but it did not work reliably. .NET Core throws instead.
Assert.Throws<InvalidOperationException>(() => { t.CurrentCulture = culture; });
Assert.Throws<InvalidOperationException>(() => { t.CurrentUICulture = uiCulture; });
Assert.Throws<InvalidOperationException>(() => t.CurrentCulture);
Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture);
t.Join();
exceptionFromThread?.Throw();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentCultureTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var t = Thread.CurrentThread;
var originalCulture = CultureInfo.CurrentCulture;
var originalUICulture = CultureInfo.CurrentUICulture;
var otherCulture = CultureInfo.InvariantCulture;
// Culture properties return the same value as those on CultureInfo
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
try
{
// Changing culture properties on CultureInfo causes the values of properties on the current thread to change
CultureInfo.CurrentCulture = otherCulture;
CultureInfo.CurrentUICulture = otherCulture;
Assert.Equal(otherCulture, t.CurrentCulture);
Assert.Equal(otherCulture, t.CurrentUICulture);
// Changing culture properties on the current thread causes new values to be returned, and causes the values of
// properties on CultureInfo to change
t.CurrentCulture = originalCulture;
t.CurrentUICulture = originalUICulture;
Assert.Equal(originalCulture, t.CurrentCulture);
Assert.Equal(originalUICulture, t.CurrentUICulture);
Assert.Equal(originalCulture, CultureInfo.CurrentCulture);
Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture);
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
CultureInfo.CurrentUICulture = originalUICulture;
}
Assert.Throws<ArgumentNullException>(() => t.CurrentCulture = null);
Assert.Throws<ArgumentNullException>(() => t.CurrentUICulture = null);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentPrincipalTest_SkipOnDesktopFramework()
{
ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Null(Thread.CurrentPrincipal));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentPrincipalTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var originalPrincipal = Thread.CurrentPrincipal;
var otherPrincipal =
new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[] { string.Empty });
Thread.CurrentPrincipal = otherPrincipal;
Assert.Equal(otherPrincipal, Thread.CurrentPrincipal);
Thread.CurrentPrincipal = originalPrincipal;
Assert.Equal(originalPrincipal, Thread.CurrentPrincipal);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentPrincipalContextFlowTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(async () =>
{
Thread.CurrentPrincipal = new ClaimsPrincipal();
await Task.Run(async () =>
{
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
await Task.Run(async () =>
{
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("name"), new string[0]);
await Task.Run(() =>
{
Assert.IsType<GenericPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<GenericPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
});
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentPrincipalContextFlowTest_NotFlow()
{
ThreadTestHelpers.RunTestInBackgroundThread(async () =>
{
Thread.CurrentPrincipal = new ClaimsPrincipal();
Task task;
using (ExecutionContext.SuppressFlow())
{
Assert.True(ExecutionContext.IsFlowSuppressed());
task = Task.Run(() =>
{
Assert.Null(Thread.CurrentPrincipal);
Assert.False(ExecutionContext.IsFlowSuppressed());
});
}
Assert.False(ExecutionContext.IsFlowSuppressed());
await task;
});
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void CurrentPrincipal_SetNull()
{
// We run test on remote process because we need to set same principal policy
// On .NET Framework default principal policy is PrincipalPolicy.UnauthenticatedPrincipal
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.NoPrincipal);
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = null;
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new ClaimsPrincipal();
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = null;
Assert.Null(Thread.CurrentPrincipal);
Thread.CurrentPrincipal = new ClaimsPrincipal();
Assert.IsType<ClaimsPrincipal>(Thread.CurrentPrincipal);
}).Dispose();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void CurrentThreadTest()
{
Thread otherThread = null;
var t = new Thread(() => otherThread = Thread.CurrentThread);
t.IsBackground = true;
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.Equal(t, otherThread);
var mainThread = Thread.CurrentThread;
Assert.NotNull(mainThread);
Assert.NotEqual(mainThread, otherThread);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ExecutionContextTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(
() => Assert.Equal(ExecutionContext.Capture(), Thread.CurrentThread.ExecutionContext));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void IsAliveTest()
{
var isAliveWhenRunning = false;
Thread t = null;
t = new Thread(() => isAliveWhenRunning = t.IsAlive);
t.IsBackground = true;
Assert.False(t.IsAlive);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.True(isAliveWhenRunning);
Assert.False(t.IsAlive);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void IsBackgroundTest()
{
var t = new Thread(() => { });
Assert.False(t.IsBackground);
t.IsBackground = true;
Assert.True(t.IsBackground);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
// Cannot use this property after the thread is dead
Assert.Throws<ThreadStateException>(() => t.IsBackground);
Assert.Throws<ThreadStateException>(() => t.IsBackground = false);
Assert.Throws<ThreadStateException>(() => t.IsBackground = true);
// Verify that the test process can shut down gracefully with a hung background thread
t = new Thread(() => Thread.Sleep(Timeout.Infinite));
t.IsBackground = true;
t.Start();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void IsThreadPoolThreadTest()
{
var isThreadPoolThread = false;
Thread t = null;
t = new Thread(() => { isThreadPoolThread = t.IsThreadPoolThread; });
t.IsBackground = true;
Assert.False(t.IsThreadPoolThread);
t.Start();
Assert.True(t.Join(UnexpectedTimeoutMilliseconds));
Assert.False(isThreadPoolThread);
var e = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
state =>
{
isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread;
e.Set();
});
e.CheckedWait();
Assert.True(isThreadPoolThread);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ManagedThreadIdTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
t.Start();
Assert.NotEqual(Environment.CurrentManagedThreadId, t.ManagedThreadId);
e.Set();
waitForThread();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void NameTest()
{
string name = Guid.NewGuid().ToString("N");
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
var ct = Thread.CurrentThread;
Assert.Equal(name, ct.Name);
ct.Name = name + "xyz";
Assert.Equal(name + "xyz", ct.Name);
ct.Name = null;
Assert.Null(ct.Name);
ct.Name = name;
Assert.Equal(name, ct.Name);
});
t.IsBackground = true;
Assert.Null(t.Name);
t.Name = null;
Assert.Null(t.Name);
t.Name = name + "xyz";
Assert.Equal(name + "xyz", t.Name);
t.Name = name;
Assert.Equal(name, t.Name);
t.Start();
waitForThread();
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var ct = Thread.CurrentThread;
Assert.Null(ct.Name);
ct.Name = name;
Assert.Equal(name, ct.Name);
ct.Name = name + "xyz";
Assert.Equal(name + "xyz", ct.Name);
ct.Name = null;
Assert.Null(ct.Name);
ct.Name = name;
Assert.Equal(name, ct.Name);
});
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void ThreadNameDoesNotAffectProcessName()
{
// On Linux, changing the main thread name affects ProcessName.
// To avoid that, .NET ignores requests to change the main thread name.
RemoteExecutor.Invoke(() =>
{
const string ThreadName = "my-thread";
Thread.CurrentThread.Name = ThreadName;
Assert.Equal(ThreadName, Thread.CurrentThread.Name);
Assert.NotEqual(ThreadName, Process.GetCurrentProcess().ProcessName);
}).Dispose();
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/72246", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void PriorityTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Assert.Equal(ThreadPriority.Normal, t.Priority);
t.Priority = ThreadPriority.AboveNormal;
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Start();
Assert.Equal(ThreadPriority.AboveNormal, t.Priority);
t.Priority = ThreadPriority.Normal;
Assert.Equal(ThreadPriority.Normal, t.Priority);
e.Set();
waitForThread();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void ThreadStateTest()
{
var e0 = new ManualResetEvent(false);
var e1 = new AutoResetEvent(false);
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
e0.CheckedWait();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0));
});
Assert.Equal(ThreadState.Unstarted, t.ThreadState);
t.IsBackground = true;
Assert.Equal(ThreadState.Unstarted | ThreadState.Background, t.ThreadState);
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.WaitSleepJoin | ThreadState.Background));
e0.Set();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.Running | ThreadState.Background));
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
t = ThreadTestHelpers.CreateGuardedThread(
out waitForThread,
() => ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0)));
t.Start();
ThreadTestHelpers.WaitForCondition(() => t.ThreadState == ThreadState.Running);
e1.Set();
waitForThread();
Assert.Equal(ThreadState.Stopped, t.ThreadState);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void AbortSuspendTest()
{
var e = new ManualResetEvent(false);
Action waitForThread;
var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
t.IsBackground = true;
Action verify = () =>
{
#pragma warning disable SYSLIB0006, 618 // Obsolete: Abort, Suspend, Resume, ResetAbort
Assert.Throws<PlatformNotSupportedException>(() => t.Abort());
Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t));
Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort());
Assert.Throws<PlatformNotSupportedException>(() => t.Suspend());
Assert.Throws<PlatformNotSupportedException>(() => t.Resume());
#pragma warning restore SYSLIB0006, 618 // Obsolete: Abort, Suspend, Resume, ResetAbort
};
verify();
t.Start();
verify();
e.Set();
waitForThread();
}
private static void VerifyLocalDataSlot(LocalDataStoreSlot slot)
{
Assert.NotNull(slot);
var waitForThreadArray = new Action[2];
var threadArray = new Thread[2];
var barrier = new Barrier(threadArray.Length);
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
Func<bool> barrierSignalAndWait =
() =>
{
try
{
Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken));
}
catch (OperationCanceledException)
{
return false;
}
return true;
};
Action<int> threadMain =
threadIndex =>
{
try
{
Assert.Null(Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex == 0)
{
Assert.Equal(threadIndex, Thread.GetData(slot));
}
else
{
Assert.Null(Thread.GetData(slot));
}
if (!barrierSignalAndWait())
{
return;
}
if (threadIndex != 0)
{
Thread.SetData(slot, threadIndex);
}
if (!barrierSignalAndWait())
{
return;
}
Assert.Equal(threadIndex, Thread.GetData(slot));
if (!barrierSignalAndWait())
{
return;
}
}
catch (Exception ex)
{
cancellationTokenSource.Cancel();
throw new TargetInvocationException(ex);
}
};
for (int i = 0; i < threadArray.Length; ++i)
{
threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i));
threadArray[i].IsBackground = true;
threadArray[i].Start();
}
foreach (var waitForThread in waitForThreadArray)
{
waitForThread();
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void LocalDataSlotTest()
{
var slot = Thread.AllocateDataSlot();
var slot2 = Thread.AllocateDataSlot();
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
var slotName = "System.Threading.Threads.Tests.LocalDataSlotTest";
var slotName2 = slotName + ".2";
var invalidSlotName = slotName + ".Invalid";
try
{
// AllocateNamedDataSlot allocates
slot = Thread.AllocateNamedDataSlot(slotName);
AssertExtensions.Throws<ArgumentException>(null, () => Thread.AllocateNamedDataSlot(slotName));
slot2 = Thread.AllocateNamedDataSlot(slotName2);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
// Free the same slot twice, should be fine
Thread.FreeNamedDataSlot(slotName2);
Thread.FreeNamedDataSlot(slotName2);
}
catch (Exception ex)
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
throw new TargetInvocationException(ex);
}
try
{
// GetNamedDataSlot gets or allocates
var tempSlot = Thread.GetNamedDataSlot(slotName);
Assert.Equal(slot, tempSlot);
tempSlot = Thread.GetNamedDataSlot(slotName2);
Assert.NotEqual(slot2, tempSlot);
slot2 = tempSlot;
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
try
{
// A named slot can be used after the name is freed, since only the name is freed, not the slot
slot = Thread.AllocateNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName);
slot2 = Thread.AllocateNamedDataSlot(slotName); // same name
Thread.FreeNamedDataSlot(slotName);
Assert.NotEqual(slot, slot2);
VerifyLocalDataSlot(slot);
VerifyLocalDataSlot(slot2);
}
finally
{
Thread.FreeNamedDataSlot(slotName);
Thread.FreeNamedDataSlot(slotName2);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/69919", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
public static void InterruptTest()
{
// Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets
// interrupted and does not auto-reset the signaled event
var threadReady = new AutoResetEvent(false);
var continueThread = new AutoResetEvent(false);
bool continueThreadBool = false;
Action waitForThread;
var t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
threadReady.Set();
ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool));
threadReady.Set();
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
});
t.IsBackground = true;
t.Start();
threadReady.CheckedWait();
continueThread.Set();
t.Interrupt();
Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds));
Volatile.Write(ref continueThreadBool, true);
waitForThread();
Assert.True(continueThread.WaitOne(0));
// Interrupting a dead thread does nothing
t.Interrupt();
// Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Interrupt();
t.Start();
waitForThread();
// A thread that is already blocked on a synchronization primitive unblocks immediately
continueThread.Reset();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
t.IsBackground = true;
t.Start();
ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0);
t.Interrupt();
waitForThread();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/69919", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/49521", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework()
{
// A wait in a finally block can be interrupted. The .NET Framework applies the same rules as thread abort, and
// does not allow thread interrupt in a finally block. There is nothing special about thread interrupt that requires
// not allowing it in finally blocks, so this behavior has changed in .NET Core.
var continueThread = new AutoResetEvent(false);
Action waitForThread;
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
try
{
}
finally
{
Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
}
});
t.IsBackground = true;
t.Start();
t.Interrupt();
waitForThread();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static void JoinTest()
{
var threadReady = new ManualResetEvent(false);
var continueThread = new ManualResetEvent(false);
Action waitForThread;