@@ -9,53 +9,37 @@ namespace AustinHarris.JsonRpc.Client
99{
1010 public class InProcessClient
1111 {
12- private static Dictionary < long , AustinHarris . JsonRpc . JsonResponse > results = new Dictionary < long , AustinHarris . JsonRpc . JsonResponse > ( ) ;
13- private static Dictionary < long , ManualResetEvent > resultSignals = new Dictionary < long , ManualResetEvent > ( ) ;
1412 /// <summary>
15- /// This is not very performant with all the conversions going on.
13+ /// Simple wrapper around JsonRpcProcessor.Process
1614 /// </summary>
1715 /// <param name="jsonrpc"></param>
1816 /// <returns></returns>
1917 public static Task < string > Invoke ( string jsonrpc )
2018 {
2119 var request = Newtonsoft . Json . JsonConvert . DeserializeObject < AustinHarris . JsonRpc . JsonRequest > ( jsonrpc ) ;
20+ var taskSource = new TaskCompletionSource < string > ( ) ;
2221
23- // we need to remember this ID so we can return a task when we get a response with this ID.
24- var resultTask = Task < string > . Factory . StartNew ( _id =>
25- {
26- var myid = ( long ) _id ;
27-
28- ManualResetEvent mr = new ManualResetEvent ( false ) ;
29- resultSignals [ myid ] = mr ;
30- mr . WaitOne ( ) ;
31- var result = results [ myid ] ;
32- // clean up dictionary
33- results . Remove ( myid ) ;
34- resultSignals . Remove ( myid ) ;
35- return Newtonsoft . Json . JsonConvert . SerializeObject ( result ) ;
36- } , request . Id ) ; // Probly need to add a continuation to check for errors and
37- // clean up our dictionarys there also..
38-
39- var rpcResultHandler = new AsyncCallback ( _ =>
40- {
41- var response = ( ( JsonRpcStateAsync ) _ ) . Result ;
42- DispatchResults ( Newtonsoft . Json . JsonConvert . DeserializeObject < AustinHarris . JsonRpc . JsonResponse > ( response ) ) ;
43- } ) ;
22+ var mc = new IAsyncWrapper ( taskSource ) ;
4423
45- var async = new JsonRpcStateAsync ( rpcResultHandler , null ) ;
24+ var async = new JsonRpcStateAsync ( mc . AsyncCallback , null ) ;
4625 async . JsonRpc = jsonrpc ;
4726 JsonRpcProcessor . Process ( async ) ;
4827
49- return resultTask ;
28+ return taskSource . Task ;
5029 }
5130
52- private static void DispatchResults ( JsonResponse response )
31+ private class IAsyncWrapper
5332 {
54- // find our signal and result dictionary.
55- var signal = resultSignals [ ( long ) response . Id ] ; // must be long
56- // store our result
57- results [ ( long ) response . Id ] = response ;
58- signal . Set ( ) ;
33+ TaskCompletionSource < string > foo ;
34+ public IAsyncWrapper ( TaskCompletionSource < string > item )
35+ {
36+ foo = item ;
37+ }
38+
39+ public void AsyncCallback ( IAsyncResult ar )
40+ {
41+ foo . SetResult ( ( ( JsonRpcStateAsync ) ar ) . Result ) ;
42+ }
5943 }
6044 }
6145}
0 commit comments