コード例 #1
0
        /// <summary>
        /// Invokes the JavaScript function registered with the specified identifier.
        /// Arguments and return values are marshalled via JSON serialization.
        /// </summary>
        /// <typeparam name="TRes">The .NET type corresponding to the function's return value type. This type must be JSON deserializable.</typeparam>
        /// <param name="identifier">The identifier used when registering the target function.</param>
        /// <param name="args">The arguments to pass, each of which must be JSON serializable.</param>
        /// <returns>The result of the function invocation.</returns>
        public static Task <TRes> InvokeAsync <TRes>(string identifier, params object[] args)
        {
            var tcs        = new TaskCompletionSource <TRes>();
            var callbackId = Guid.NewGuid().ToString();
            var argsJson   = new string[args.Length + 2];

            argsJson[0] = identifier;
            argsJson[1] = callbackId;
            for (int i = 0; i < args.Length; i++)
            {
                argsJson[i + 2] = JsonUtil.Serialize(args[i]);
            }

            TaskCallbacks.Track(callbackId, new Action <string>(r =>
            {
                var res = JsonUtil.Deserialize <InvocationResult <TRes> >(r);
                TaskCallbacks.Untrack(callbackId);
                if (res.Succeeded)
                {
                    tcs.SetResult(res.Result);
                }
                else
                {
                    tcs.SetException(new JavaScriptException(res.Message));
                }
            }));

            try
            {
                var result = Invoke <object>("invokeWithJsonMarshallingAsync", argsJson);
            }
            catch
            {
                TaskCallbacks.Untrack(callbackId);
                throw;
            }

            return(tcs.Task);
        }
コード例 #2
0
        public static void InvokeTaskCallback(string id, string result)
        {
            var callback = TaskCallbacks.Get(id);

            callback(result);
        }