コード例 #1
0
ファイル: CallProxy.cs プロジェクト: VitalElement/AsyncRpc
        public object Invoke(MethodInfo method, IEnumerable args)
        {
            var  ms           = new MemoryStream();
            Type expectedType = null;

            _serializer.SerializeCall(ms, _binder, _targetName, new MethodCall
            {
                Method    = method,
                Arguments = args.Cast <object>().ToArray()
            });

            ITaskCompletionSource tcs;

            if (method.ReturnType == typeof(Task))
            {
                tcs = new TcsWrapper <object> ();
            }
            else if (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
            {
                expectedType = method.ReturnType.GetGenericArguments()[0];
                tcs          = (ITaskCompletionSource)
                               Activator.CreateInstance(
                    typeof(TcsWrapper <>).MakeGenericType(expectedType));
            }
            else
            {
                throw new InvalidOperationException("Non Task/Task<T> return values aren't supported");
            }

            SendAndParseResponse(ms.ToArray(), expectedType).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.SetException(t.Exception);
                    return;
                }
                var rslt = t.Result;
                if (rslt.Exception != null)
                {
                    tcs.SetException(new Exception(rslt.Exception));
                }
                else
                {
                    tcs.SetResultOrCastException(rslt.Result);
                }
            });
            return(tcs.Task);
        }
コード例 #2
0
        public async Task <T> Invoke <T>(MethodInfo method, IEnumerable args)
        {
            using var ms = new RecyclableMemoryStream(StreamPool.Shared);
            _serializer.SerializeCall(ms, _binder, _targetName, new MethodCall
            {
                Method    = method,
                Arguments = args.Cast <object>().ToArray()
            });
            ms.Position = 0;
            var res = await SendAndParseResponse(ms, typeof(T));

            if (res.Exception != null)
            {
                throw new Exception(res.Exception);
            }
            return((T)res.Result);
        }