1- // Copyright (c) Microsoft Corporation.
1+ // Copyright (c) Microsoft Corporation.
22// Licensed under the MIT License.
33
44using System ;
55using System . Collections . Generic ;
6+ using System . Threading ;
67using System . Threading . Tasks ;
78
89namespace Microsoft . JavaScript . NodeApi . TestCases ;
@@ -36,7 +37,7 @@ private static void ValidateNotOnJSThread()
3637
3738 public static async Task CallDelegateFromOtherThread ( Action action )
3839 {
39- await Task . Run ( ( ) =>
40+ await RunInThread ( ( ) =>
4041 {
4142 ValidateNotOnJSThread ( ) ;
4243
@@ -48,7 +49,7 @@ public static async Task<string> CallInterfaceMethodFromOtherThread(
4849 ISmpleInterface interfaceObj ,
4950 string value )
5051 {
51- return await Task . Run ( ( ) =>
52+ return await RunInThread ( ( ) =>
5253 {
5354 ValidateNotOnJSThread ( ) ;
5455
@@ -59,7 +60,7 @@ public static async Task<string> CallInterfaceMethodFromOtherThread(
5960 public static async Task < int > EnumerateCollectionFromOtherThread (
6061 IReadOnlyCollection < int > collection )
6162 {
62- return await Task . Run ( ( ) =>
63+ return await RunInThread ( ( ) =>
6364 {
6465 ValidateNotOnJSThread ( ) ;
6566
@@ -76,7 +77,7 @@ public static async Task<int> EnumerateCollectionFromOtherThread(
7677 public static async Task < int > EnumerateDictionaryFromOtherThread (
7778 IReadOnlyDictionary < string , string > dictionary )
7879 {
79- return await Task . Run ( ( ) =>
80+ return await RunInThread ( ( ) =>
8081 {
8182 ValidateNotOnJSThread ( ) ;
8283
@@ -93,11 +94,52 @@ public static async Task<int> EnumerateDictionaryFromOtherThread(
9394 public static async Task < bool > ModifyDictionaryFromOtherThread (
9495 IDictionary < string , string > dictionary , string keyToRemove )
9596 {
96- return await Task . Run ( ( ) =>
97+ return await RunInThread ( ( ) =>
9798 {
9899 ValidateNotOnJSThread ( ) ;
99100
100101 return dictionary . Remove ( keyToRemove ) ;
101102 } ) ;
102103 }
104+
105+ private static Task RunInThread ( Action action )
106+ {
107+ TaskCompletionSource < bool > threadCompletion = new TaskCompletionSource < bool > ( ) ;
108+
109+ Thread thread = new Thread ( ( ) =>
110+ {
111+ try
112+ {
113+ action ( ) ;
114+ threadCompletion . TrySetResult ( true ) ;
115+ }
116+ catch ( Exception e )
117+ {
118+ threadCompletion . TrySetException ( e ) ;
119+ }
120+ } ) ;
121+ thread . Start ( ) ;
122+
123+ return threadCompletion . Task ;
124+ }
125+
126+ private static Task < T > RunInThread < T > ( Func < T > func )
127+ {
128+ TaskCompletionSource < T > threadCompletion = new TaskCompletionSource < T > ( ) ;
129+
130+ Thread thread = new Thread ( ( ) =>
131+ {
132+ try
133+ {
134+ threadCompletion . TrySetResult ( func ( ) ) ;
135+ }
136+ catch ( Exception e )
137+ {
138+ threadCompletion . TrySetException ( e ) ;
139+ }
140+ } ) ;
141+ thread . Start ( ) ;
142+
143+ return threadCompletion . Task ;
144+ }
103145}
0 commit comments