Example #1
0
        public static void RunTest(TestType type, int ThreadCount, CallbackFunction callBack, ITest target)
        {
            for (int i = 0; i < ThreadCount; i++)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (object sender, DoWorkEventArgs e) =>
                {
                    bool result = target.Test();
                    e.Result = result;

                };

                worker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
                    {
                        if (callBack != null)
                        {
                            if (e.Error != null)
                            {
                                callBack(type, (bool)e.Result);
                            }
                            else
                            {
                                callBack(type, false);
                            }
                        }
                    };
                worker.RunWorkerAsync();
            }
        }
        public void Load(string collectionName, CallbackFunction.Load<IList<JsonDocument>> callback)
        {
            Guard.Assert(() => !string.IsNullOrEmpty(collectionName));
            Guard.Assert(() => callback != null);

            SynchronizationContext context = SynchronizationContext.Current;

            IndexSession.Query("Raven/DocumentsByEntityName", new IndexQuery {Query = string.Format("Tag:{0}", collectionName)}, null, (result) =>
                                                                                                                                           {
                                                                                                                                               var documents = new List<JsonDocument>();

                                                                                                                                               if (result.IsSuccess)
                                                                                                                                               {
                                                                                                                                                   var jsonSerializer = new JsonSerializer();
                                                                                                                                                   documents =
                                                                                                                                                       result.Data.Results.Select(
                                                                                                                                                           document =>
                                                                                                                                                           (JsonDocument) jsonSerializer.Deserialize(document.CreateReader(), typeof (JsonDocument))).
                                                                                                                                                           ToList();
                                                                                                                                               }

                                                                                                                                               var loadResponse = new LoadResponse<IList<JsonDocument>>
                                                                                                                                                                      {
                                                                                                                                                                          Data = documents,
                                                                                                                                                                          Exception = result.Exception,
                                                                                                                                                                          StatusCode = result.StatusCode
                                                                                                                                                                      };

                                                                                                                                               context.Post(delegate { callback.Invoke(loadResponse); },
                                                                                                                                                            null);
                                                                                                                                           });
        }
Example #3
0
 public static void RegisterTriggerRule(CallbackFunction c, TestTriggerCondition f)
 {
     lock (mutex)
     {
         if (!hash.ContainsKey(c) || hash[c] != f)
             hash.Add(c, f);
     }
 }
Example #4
0
 public static void UnregisterTriggerRule(CallbackFunction c, TestTriggerCondition f)
 {
     lock (mutex)
     {
         if (hash.ContainsKey(c) && hash[c] == f)
             hash.Remove(c);
     }
 }
Example #5
0
 private static void CheckCallDelayed()
 {
     if (Time.realtimeSinceStartup > s_DelayedCallbackTime)
     {
         update = (CallbackFunction) Delegate.Remove(update, new CallbackFunction(EditorApplication.CheckCallDelayed));
         delayedCallback();
     }
 }
Example #6
0
 private static void Internal_CallDelayFunctions()
 {
     CallbackFunction delayCall = EditorApplication.delayCall;
     EditorApplication.delayCall = null;
     if (delayCall != null)
     {
         delayCall();
     }
 }
Example #7
0
 public void ExecuteDelegate(CallbackFunction function)
 {
     if (function != null)
     {
         function();
     }
     HideDialog();
     Button1.onClick.RemoveAllListeners();
     Button2.onClick.RemoveAllListeners();
 }
Example #8
0
 public static void UnregisterTriggerRule(CallbackFunction c, TestTriggerCondition f)
 {
     lock (mutex)
     {
         if (hash.ContainsKey(c) && hash[c] == f)
         {
             hash.Remove(c);
         }
     }
 }
Example #9
0
 public static void RegisterTriggerRule(CallbackFunction c, TestTriggerCondition f)
 {
     lock (mutex)
     {
         if (!hash.ContainsKey(c) || hash[c] != f)
         {
             hash.Add(c, f);
         }
     }
 }
Example #10
0
        private static void Internal_CallDelayFunctions()
        {
            CallbackFunction delayCall = EditorApplication.delayCall;

            EditorApplication.delayCall = null;
            if (delayCall != null)
            {
                delayCall();
            }
        }
Example #11
0
    private IEnumerator GetUserData(CallbackFunction callback)
    {
        WWW www = new WWW("https://randomuser.me/api");

        yield return(www);

        string returnString = www.text;

        Debug.Log(returnString);
    }
Example #12
0
        public ErrorMessage(string errorText, CallbackFunction callback)
        {
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            DialogResult      result  = MessageBox.Show(errorText, "Error", buttons, MessageBoxIcon.Error);

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                callback?.Invoke();
            }
        }
    public void PlayMissionCompletedTransition(CallbackFunction callbackFunction)
    {
        _callbackFunction = callbackFunction;

        _animationList = new List <SceneTransitionAnimation>();
        _animationList.Add(new TransitionAnimationWait(1f));
        _animationList.Add(new TransitionAnimationSwipe(canvas, transitionSwipeObject /*transitionSwipePrefab*/, 1f, false));

        StartAnimation();
    }
        public virtual void Invoke(IV8PluginRouter router, CefV8Context context, object result, int errorCode, string error)
        {
            if (CallbackFunction == null)
            {
                throw new ObjectDisposedException("_callback");
            }

            // Have to enter the context in order to be able to create object/array/function/date V8 instances
            context.Enter();
            try
            {
                var args = new List <CefV8Value>();
                switch (_callbackType)
                {
                case V8CallbackType.ParameterCallback:
                case V8CallbackType.EventListener:
                {
                    var remoteResult = result as ResultData;
                    var localArray   = result as object[];

                    if (remoteResult != null)
                    {
                        if (remoteResult.Items != null)
                        {
                            args.AddRange(remoteResult.Items.Select(item => ToCefV8Value(router, item)));
                        }
                    }
                    else if (localArray != null)
                    {
                        args.AddRange(localArray.Select(item => ToCefV8Value(router, item)));
                    }

                    break;
                }

                case V8CallbackType.FunctionCallback:
                {
                    args.Add(ToCefV8Value(router, result));
                    args.Add(CefV8Value.CreateInt(errorCode));
                    args.Add(CefV8Value.CreateString(error));
                    break;
                }
                }
                var functionResult = CallbackFunction.ExecuteFunction(null, args.ToArray());
                if (functionResult == null && CallbackFunction.HasException)
                {
                    var exception = CallbackFunction.GetException();
                    Logger.Error("Error executing callback: ", exception.Message);
                }
            }
            finally
            {
                context.Exit();
            }
        }
Example #15
0
 public ADData(MccBoard board, BoardConfiguration bc)
 {
     lowChannel = bc.LowChannel;
     qChans = bc.QChanns;
     NumPoints = 186;//bc.PointsRead;
     MemHandle = MccDaq.MccService.WinBufAllocEx(10*qChans*NumPoints);
     Board = board;
     rate = bc.Rate;
     adData = new ushort[qChans*NumPoints];
     mCb = new CallbackFunction(this.CreateBackground);
 }
Example #16
0
        /// <summary>
        /// Create a new TCP listener on the default port and create a new ConnectionState,
        /// then begin listening for clients on the default port
        /// </summary>
        /// <param name="connectedCallback"></param>
        public static void ServerAwaitingClientLoop(CallbackFunction connectedCallback)
        {
            TcpListener lstn = new TcpListener(IPAddress.Any, DEFAULT_PORT);

            lstn.Start();
            ConnectionState cs = new ConnectionState();

            cs.listener       = lstn;
            cs.EventProcessor = connectedCallback;
            lstn.BeginAcceptSocket(AcceptNewClient, cs);
        }
Example #17
0
        /// <summary>
        /// Start attempting to connect to the server
        /// </summary>
        /// <param name="host_name"> server to connect to </param>
        /// <returns></returns>
        public static Socket ConnectToServer(string hostName, int port, CallbackFunction connectedCallback)
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                IPHostEntry ipHostInfo;
                IPAddress   ipAddress = IPAddress.None;

                // Determine if the server address is a URL or an IP
                try
                {
                    ipHostInfo = Dns.GetHostEntry(hostName);
                    bool foundIPV4 = false;
                    foreach (IPAddress addr in ipHostInfo.AddressList)
                    {
                        if (addr.AddressFamily != AddressFamily.InterNetworkV6)
                        {
                            foundIPV4 = true;
                            ipAddress = addr;
                            break;
                        }
                    }
                    // Didn't find any IPV4 addresses
                    if (!foundIPV4)
                    {
                        Debug.WriteLine("Could not find IP");
                        return(null);
                    }
                }
                catch (Exception e1)
                {
                    // see if host name is actually an ipaddress, i.e., 155.99.123.456
                    ipAddress = IPAddress.Parse(hostName);
                }


                // Create a TCP/IP socket.
                Socket theServer = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                theServer.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
                SocketState serverState = new SocketState(theServer, -1);

                // store the action for when first conectting to the server.
                serverState.EventProcessor = connectedCallback;

                serverState.socket.BeginConnect(ipAddress, port, ConnectedToServer, serverState);
                //serverState.socket.Connect(ipAddress, 2112);
                return(theServer);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #18
0
 /// <summary>
 /// Receives an item from the cache or loads it
 /// </summary>
 /// <param name="key">to lookup</param>
 /// <param name="callback">to be calles when loaded</param>
 public void Get(TKey key, CallbackFunction callback)
 {
     if (storage.ContainsKey(key))
     {
         callback(storage[key]);
     }
     else
     {
         enqueue(key, callback);
     }
 }
Example #19
0
 public static void DelayCall(CallbackFunction method)
 {
                 #if UNITY_EDITOR
     if (EditorApplication.delayCall != method)
     {
         EditorApplication.delayCall += method;
     }
     return;
                 #endif
     Utility.DelayCall(method, 0);
 }
        static void Internal_CallDelayFunctions()
        {
            CallbackFunction delay = delayCall;

            delayCall = null;

            if (delay != null)
            {
                delay();
            }
        }
Example #21
0
        public static void DelayCall(Action method)
        {
#if UNITY_EDITOR
            CallbackFunction callback = new CallbackFunction(method);
            if (EditorApplication.delayCall != callback)
            {
                EditorApplication.delayCall += callback;
            }
            return;
#endif
            Utility.DelayCall(method, 0);
        }
Example #22
0
        /// <summary>
        /// Releases all resource used by the <see cref="LuaSharp.ClrFunction"/> object.
        /// </summary>
        /// <remarks>
        /// Call <see cref="Dispose"/> when you are finished using the <see cref="LuaSharp.ClrFunction"/>. The
        /// <see cref="Dispose"/> method leaves the <see cref="LuaSharp.ClrFunction"/> in an unusable state. After calling
        /// <see cref="Dispose"/>, you must release all references to the <see cref="LuaSharp.ClrFunction"/> so the garbage
        /// collector can reclaim the memory that the <see cref="LuaSharp.ClrFunction"/> was occupying.
        /// </remarks>
        public void Dispose()
        {
            var wasDisposed = Interlocked.Exchange( ref disposed, 1 ) == 1;
            if( wasDisposed )
                return;

            callback = null;
            name = null;

            Dispose( true );
            GC.SuppressFinalize( this );
        }
Example #23
0
        /// <summary>
        ///     Enqueues the work item. Returns a work-item-state-struct as a handle to the operation that is just about, or
        ///     queued, to be executed.
        ///     <para>Information on the returned struct... </para>
        ///     <para>
        ///         Call the result property on this struct to trigger a lock, thus blocking your current thread until the function
        ///         has executed.
        ///     </para>
        ///     <para>
        ///         Call Dispose on that returned item to automatically reuse the data-structure behind each work-item in order to
        ///         avoid
        ///         garbage-collector-cycles.
        ///     </para>
        ///     <para>
        ///         Use its <c>IsCompleted</c>-Property to verify within a monitor if your method has finished executing. The
        ///         <c>IsCompleted</c>-Property actually triggers a WaitOne(1) on a
        ///         ManualResetEvent internally thus returning almost instantly.
        ///     </para>
        /// </summary>
        /// <typeparam name="V">The type of the result.</typeparam>
        /// <param name="workerFunction">The worker function.</param>
        /// <param name="asyncCallback">The async callback.</param>
        /// <returns>
        ///     Returns a work-item-state-struct as a handle to the operation that is just about, or queued, to be executed.
        /// </returns>
        public IWorkItemState <V> EnqueueWorkItem <V>(Func <V> workerFunction, CallbackFunction asyncCallback = null)
        {
            var workItem = GetWorkItem(asyncCallback);

            workItem.DelegateInputParameters = new object[] {};
            workItem.Delegate = delegateInputParameters => { return(workerFunction.Invoke()); };

            var workItemState = new WorkItemState <V>(workItem.WorkItemStateTypeless);

            EnqueueWorkItemInternal(workItem);
            return(workItemState);
        }
Example #24
0
        public void testTail()
        {
            var lua = @"    
                print(tail)
                tail(100)
            ";

            //var script = new Script();
            script.Globals["tail"] = DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Func <int, DynValue>)newTail));
            script.DoString(lua);

            Console.ReadKey();
        }
Example #25
0
        /// <summary>
        ///     Enqueues the work item. Returns a work-item-state-struct as a handle to the operation that is just about, or
        ///     queued, to be executed.
        ///     <para>Information on the returned struct... </para>
        ///     <para>
        ///         Call the result property on this struct to trigger a lock, thus blocking your current thread until the function
        ///         has executed.
        ///     </para>
        ///     <para>
        ///         Call Dispose on that returned item to automatically reuse the data-structure behind each work-item in order to
        ///         avoid
        ///         garbage-collector-cycles.
        ///     </para>
        ///     <para>
        ///         Use its <c>IsCompleted</c>-Property to verify within a monitor if your method has finished executing. The
        ///         <c>IsCompleted</c>-Property actually triggers a WaitOne(1) on a
        ///         ManualResetEvent internally thus returning almost instantly.
        ///     </para>
        /// </summary>
        /// <typeparam name="T1">The type of the 1.</typeparam>
        /// <typeparam name="T2">The type of the 2.</typeparam>
        /// <typeparam name="V">The type of the result.</typeparam>
        /// <param name="workerFunction">The worker function.</param>
        /// <param name="arg1">The arg1.</param>
        /// <param name="arg2">The arg2.</param>
        /// <param name="asyncCallback">The async callback.</param>
        /// <returns>
        ///     Returns a work-item-state-struct as a handle to the operation that is just about, or queued, to be executed.
        /// </returns>
        public IWorkItemState <V> EnqueueWorkItem <T1, T2, V>(Func <T1, T2, V> workerFunction, T1 arg1, T2 arg2,
                                                              CallbackFunction asyncCallback = null)
        {
            var workItem = GetWorkItem(asyncCallback);

            workItem.DelegateInputParameters = new object[] { arg1, arg2 };
            workItem.Delegate = delegateInputParameters => workerFunction.Invoke(arg1, arg2);

            var workItemState = new WorkItemState <V>(workItem.WorkItemStateTypeless);

            EnqueueWorkItemInternal(workItem);
            return(workItemState);
        }
Example #26
0
 private void enqueue(TKey key, CallbackFunction callback)
 {
     if (queued.ContainsKey(key))
     {
         queued[key].Add(callback);
     }
     else
     {
         queued[key] = new List <CallbackFunction> {
             callback
         };
         load(key); // invoke the first load per key
     }
 }
Example #27
0
		public Lua()
		{
			state = LuaLib.luaL_newstate();
			
			panicFunction = ( IntPtr s ) => {
				throw new LuaException( "Error in call to Lua API: " + LuaLib.lua_tostring( s, -1 ) );
			};
			
			LuaLib.lua_atpanic( state, panicFunction );
			
			LuaLib.luaL_openlibs( state );
			
			disposed = false;
		}
Example #28
0
        public Lua()
        {
            state = LuaLib.luaL_newstate();

            panicFunction = ( IntPtr s ) => {
                throw new LuaException("Error in call to Lua API: " + LuaLib.lua_tostring(s, -1));
            };

            LuaLib.lua_atpanic(state, panicFunction);

            LuaLib.luaL_openlibs(state);

            disposed = false;
        }
Example #29
0
 public static void Delay(Action method)
 {
                 #if UNITY_EDITOR
     if (Proxy.IsEditor())
     {
         CallbackFunction callback = new CallbackFunction(method);
         if (EditorApplication.delayCall != callback)
         {
             EditorApplication.delayCall += callback;
         }
         return;
     }
                 #endif
     Call.Delay(method, 0);
 }
        public void LoadPlugins(CallbackFunction.Load<IList<KeyValuePair<string, Attachment>>> callback)
        {
            var context = SynchronizationContext.Current;

            Client.AttachmentGetAll((result) => context.Post(delegate
                                                                 {
                                                                     callback.Invoke(new LoadResponse<IList<KeyValuePair<string, Attachment>>>()
                                                                                         {
                                                                                             Data = result.Data.Where(x => x.Key.EndsWith(".xap", StringComparison.InvariantCultureIgnoreCase)).ToList(),
                                                                                             Exception = result.Exception,
                                                                                             StatusCode = result.StatusCode
                                                                                         });
                                                                 }
                                                             , null));
        }
Example #31
0
        /// <summary>
        /// Releases all resource used by the <see cref="LuaSharp.ClrFunction"/> object.
        /// </summary>
        /// <remarks>
        /// Call <see cref="Dispose"/> when you are finished using the <see cref="LuaSharp.ClrFunction"/>. The
        /// <see cref="Dispose"/> method leaves the <see cref="LuaSharp.ClrFunction"/> in an unusable state. After calling
        /// <see cref="Dispose"/>, you must release all references to the <see cref="LuaSharp.ClrFunction"/> so the garbage
        /// collector can reclaim the memory that the <see cref="LuaSharp.ClrFunction"/> was occupying.
        /// </remarks>
        public void Dispose()
        {
            var wasDisposed = Interlocked.Exchange(ref disposed, 1) == 1;

            if (wasDisposed)
            {
                return;
            }

            callback = null;
            name     = null;

            Dispose(true);
            GC.SuppressFinalize(this);
        }
Example #32
0
 public static void DelayCall(object key, CallbackFunction method, float seconds, bool overwrite = true)
 {
     if (!key.IsNull() && !method.IsNull())
     {
         if (seconds <= 0)
         {
             method();
             return;
         }
         if (Utility.delayedMethods.ContainsKey(key) && !overwrite)
         {
             return;
         }
         Utility.delayedMethods[key] = new KeyValuePair <CallbackFunction, float>(method, Time.realtimeSinceStartup + seconds);
     }
 }
Example #33
0
    /// <summary>
    /// Add a new callback function to the worker thread.
    /// </summary>
    public static void Add(CallbackFunction fn, object param)
    {
        if (mInstance == null)
        {
            GameObject go = new GameObject("_WorkerThread");
            DontDestroyOnLoad(go);
            mInstance = go.AddComponent<WorkerThread>();
            mInstance.mThread = new Thread(mInstance.ThreadFunction);
            mInstance.mThread.Start();
        }

        Entry ent = new Entry();
        ent.fnct = fn;
        ent.param = param;
        lock (mInstance) mInstance.mActive.Add(ent);
    }
Example #34
0
 /// <summary>
 /// Removes the specified function from the worker thread.
 /// </summary>
 static public void Remove(CallbackFunction fn)
 {
     if (mInstance != null)
     {
         lock (mInstance) {
             foreach (Entry ent in mInstance.mActive)
             {
                 if (ent.fnct == fn)
                 {
                     mInstance.mActive.Remove(ent);
                     break;
                 }
             }
         }
     }
 }
Example #35
0
        private WorkItem GetWorkItem(CallbackFunction asyncCallback)
        {
            WorkItem workItem;

            if (!returnedWorkItems.TryDequeue(out workItem))
            {
                workItem = new WorkItem();
                workItem.WorkItemStateTypeless = new WorkItemStateTypeless(workItem);
            }

            workItem.SingleThreadRunner = null;
            workItem.IsCompleted        = false;
            workItem.Result             = null;
            workItem.AsyncCallback      = asyncCallback;
            return(workItem);
        }
Example #36
0
		/// <summary>
		/// Creates a new instance of the <see cref="Lua"/> class.
		/// </summary>
		public Lua()
		{
			state = LuaLib.luaL_newstate();
			
			panicFunction = ( IntPtr s ) => {
				throw new LuaException( "Error in call to Lua API: " + LuaLib.lua_tostring( s, -1 ) );
			};
			
			LuaLib.lua_atpanic( state, panicFunction );
			
			LuaLib.luaL_openlibs( state );
			
			LookupTable<IntPtr, Lua>.Store( state, this );
			
			disposed = 0;
		}
Example #37
0
        /// <summary>
        /// Creates a new instance of the <see cref="Lua"/> class.
        /// </summary>
        public Lua()
        {
            state = LuaLib.luaL_newstate();

            panicFunction = ( IntPtr s ) => {
                throw new LuaException("Error in call to Lua API: " + LuaLib.lua_tostring(s, -1));
            };

            LuaLib.lua_atpanic(state, panicFunction);

            LuaLib.luaL_openlibs(state);

            LookupTable <IntPtr, Lua> .Store(state, this);

            disposed = 0;
        }
Example #38
0
        unsafe public bool Init_USB()
        {
            char[] name  = new char[64];
            char[] model = new char[64];
            int[]  type  = new int[1];
            connected = false;

            try
            {
                if (File.Exists("ExtIO_Si570_usb.dll"))
                {
                    connected = InitHW(name, model, type);

                    if (connected)
                    {
                        callback = new CallbackFunction(ExtSi570CallbackFunction);
                        SetCallback(callback);
                        if (!console.SkinsEnabled)
                        {
                            console.btnUSB.BackColor = Color.GreenYellow;
                        }
                        console.UsbSi570Enable = true;
                    }
                    else
                    {
                        if (!console.SkinsEnabled)
                        {
                            console.SetupForm.chkGeneralUSBPresent.Checked = false;
                        }
                        console.UsbSi570Enable   = false;
                        console.btnUSB.BackColor = Color.Red;
                    }

                    return(connected);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.Write("Error while Si570 init!\n",
                            "Error!\n" + ex.ToString());
                return(false);
            }
        }
Example #39
0
    /// <summary>
    /// Add a new callback function to the worker thread.
    /// </summary>
    static public void Add(CallbackFunction fn, object param)
    {
        if (mInstance == null)
        {
            GameObject go = new GameObject("_WorkerThread");
            DontDestroyOnLoad(go);
            mInstance         = go.AddComponent <WorkerThread>();
            mInstance.mThread = new Thread(mInstance.ThreadFunction);
            mInstance.mThread.Start();
        }

        Entry ent = new Entry();

        ent.fnct  = fn;
        ent.param = param;
        lock (mInstance) mInstance.mActive.Add(ent);
    }
Example #40
0
        /// <summary>
        ///     Enqueues the work item. Returns a work-item-state-struct as a handle to the operation that is just about, or
        ///     queued, to be executed.
        ///     <para>Information on the returned struct... </para>
        ///     <para>
        ///         Call the result property on this struct to trigger a lock, thus blocking your current thread until the function
        ///         has executed.
        ///     </para>
        ///     <para>
        ///         Call Dispose on that returned item to automatically reuse the data-structure behind each work-item in order to
        ///         avoid
        ///         garbage-collector-cycles.
        ///     </para>
        ///     <para>
        ///         Use its <c>IsCompleted</c>-Property to verify within a monitor if your method has finished executing. The
        ///         <c>IsCompleted</c>-Property actually triggers a WaitOne(1) on a
        ///         <see cref="ManualResetEvent" /> internally thus returning almost instantly.
        ///     </para>
        /// </summary>
        /// <typeparam name="T1">The type of the 1.</typeparam>
        /// <typeparam name="T2">The type of the 2.</typeparam>
        /// <typeparam name="T3">The type of the 3.</typeparam>
        /// <param name="workerFunction">The worker function.</param>
        /// <param name="arg1">The arg1.</param>
        /// <param name="arg2">The arg2.</param>
        /// <param name="arg3">The arg3.</param>
        /// <param name="asyncCallback">The async callback.</param>
        /// <returns>
        ///     Returns a work-item-state-struct as a handle to the operation that is just about, or queued, to be executed.
        /// </returns>
        public IWorkItemState EnqueueWorkItem <T1, T2, T3>(Action <T1, T2, T3> workerFunction, T1 arg1, T2 arg2, T3 arg3,
                                                           CallbackFunction asyncCallback = null)
        {
            var workItem = GetWorkItem(asyncCallback);

            workItem.DelegateInputParameters = new object[] { arg1, arg2, arg3 };
            workItem.Delegate = delegateInputParameters =>
            {
                workerFunction.Invoke(arg1, arg2, arg3);
                return(null);
            };

            var workItemState = new WorkItemState(workItem.WorkItemStateTypeless);

            EnqueueWorkItemInternal(workItem);
            return(workItemState);
        }
Example #41
0
 /// <summary>
 /// Removes the specified function from the worker thread.
 /// </summary>
 public static void Remove(CallbackFunction fn)
 {
     if (mInstance != null)
     {
         lock (mInstance)
         {
             foreach (Entry ent in mInstance.mActive)
             {
                 if (ent.fnct == fn)
                 {
                     mInstance.mActive.Remove(ent);
                     break;
                 }
             }
         }
     }
 }
        public void Test_DelegateMethod(InteropAccessMode opt)
        {
            UserData.UnregisterType <SomeClass>();

            string script = @"    
				x = concat(1, 2);
				return x;"                ;

            Script S = new Script();

            SomeClass obj = new SomeClass();

            S.Globals["concat"] = CallbackFunction.FromDelegate(S, (Func <int, int, string>)obj.ConcatNums, opt);

            DynValue res = S.DoString(script);

            Assert.AreEqual(DataType.String, res.Type);
            Assert.AreEqual("1%2", res.String);
        }
Example #43
0
        public static int str_gmatch(LuaState L)
        {
            CallbackFunction C = new CallbackFunction(gmatch_aux_2, "gmatch");
            string           s = ArgAsType(L, 1, DataType.String, false).String;
            string           p = PatchPattern(ArgAsType(L, 2, DataType.String, false).String);


            C.AdditionalData = new GMatchAuxData()
            {
                S   = new CharPtr(s),
                P   = new CharPtr(p),
                LS  = (uint)s.Length,
                POS = 0
            };

            L.Push(DynValue.NewCallback(C));

            return(1);
        }
		/// <summary>
		/// Pushes a new C closure onto the stack.
		/// When a C function is created, it is possible to associate some values with it, thus creating a C closure; these values are then accessible to the function whenever it is called. To associate values with a C function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first). Then lua_pushcclosure is called to create and push the C function onto the stack, with the argument n telling how many values should be associated with the function. lua_pushcclosure also pops these values from the stack.
		/// </summary>
		/// <param name="state">
		/// A <see cref="IntPtr"/>
		/// </param>
		/// <param name="fn">
		/// A <see cref="CallbackFunction"/>
		/// </param>
		/// <param name="n">
		/// A <see cref="System.Int32"/>
		/// </param>
		public static extern void lua_pushcclosure( IntPtr state, CallbackFunction fn, int n );
		/// <summary>
		/// If an error happens outside any protected environment, Lua calls a panic function and then calls exit(EXIT_FAILURE), thus exiting the host application. Your panic function can avoid this exit by never returning (e.g., doing a long jump). The panic function can access the error message at the top of the stack.
		/// </summary>
		/// <param name="state">
		/// A Lua State. <see cref="IntPtr"/>
		/// </param>
		/// <param name="cb">
		/// A new panic function. <see cref="CallbackFunction"/>
		/// </param>
		public static extern void lua_atpanic( IntPtr state, CallbackFunction cb );
	public void SetCallback(CallbackFunction function)
	{
		m_callBack = function;	
	}
 internal static void CallDelayed(CallbackFunction function, float timeFromNow)
 {
     delayedCallback = function;
     s_DelayedCallbackTime = Time.realtimeSinceStartup + timeFromNow;
     if (<>f__mg$cache0 == null)
     {
Example #48
0
        public static int str_gmatch(LuaState L)
        {
            var C = new CallbackFunction(gmatch_aux_2, "gmatch");
            var s = ArgAsType(L, 1, DataType.String, false).String;
            var p = PatchPattern(ArgAsType(L, 2, DataType.String, false).String);


            C.AdditionalData = new GMatchAuxData
            {
                S = new CharPtr(s),
                P = new CharPtr(p),
                LS = (uint) s.Length,
                POS = 0
            };

            L.Push(DynValue.NewCallback(C));

            return 1;
        }
Example #49
0
 public void LinearQuery(string query, int start, int pageSize, CallbackFunction.Load<IList<Database.JsonDocument>> callback)
 {
     Client.LinearQuery(query, start, pageSize, callback);
 }
 public void LoadMany(CallbackFunction.Load<IList<KeyValuePair<string, Attachment>>> callback)
 {
     Client.AttachmentGetAll(callback);
 }
Example #51
0
 public static extern void SetCallback(CallbackFunction function);
Example #52
0
 public void Delete(string name, CallbackFunction.SaveOne<string> callback)
 {
     this.Client.IndexDelete(name, callback);
 }
Example #53
0
 public void Save(string name, IndexDefinition definition, CallbackFunction.SaveOne<KeyValuePair<string, IndexDefinition>> callback)
 {
     this.Client.IndexPut(name, definition, callback);
 }
Example #54
0
 public void LoadMany(CallbackFunction.Load<IDictionary<string, IndexDefinition>> callback)
 {
     this.Client.IndexGetMany(null, null, callback);
 }
		/// <summary>
		/// Pushes a C function onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type function that, when called, invokes the corresponding C function. 
		/// </summary>
		/// <param name="state">
		/// A <see cref="IntPtr"/>
		/// </param>
		/// <param name="fn">
		/// A <see cref="CallbackFunction"/>
		/// </param>
		public static void lua_pushcfunction( IntPtr state, CallbackFunction fn )
		{
			lua_pushcclosure( state, fn, 0 );
		}
		private int Internal_ExecCall(int argsCount, int instructionPtr, CallbackFunction handler = null,
			CallbackFunction continuation = null, bool thisCall = false, string debugText = null, DynValue unwindHandler = null)
		{
			DynValue fn = m_ValueStack.Peek(argsCount);
			CallStackItemFlags flags = (thisCall ? CallStackItemFlags.MethodCall : CallStackItemFlags.None);

			// if TCO threshold reached
			if ((m_ExecutionStack.Count > this.m_Script.Options.TailCallOptimizationThreshold && m_ExecutionStack.Count > 1)
				|| (m_ValueStack.Count > this.m_Script.Options.TailCallOptimizationThreshold && m_ValueStack.Count > 1))
			{
				// and the "will-be" return address is valid (we don't want to crash here)
				if (instructionPtr >= 0 && instructionPtr < this.m_RootChunk.Code.Count)
				{
					Instruction I = this.m_RootChunk.Code[instructionPtr];

					// and we are followed *exactly* by a RET 1
					if (I.OpCode == OpCode.Ret && I.NumVal == 1)
					{
						CallStackItem csi = m_ExecutionStack.Peek();

						// if the current stack item has no "odd" things pending and neither has the new coming one..
						if (csi.ClrFunction == null && csi.Continuation == null && csi.ErrorHandler == null
							&& csi.ErrorHandlerBeforeUnwind == null && continuation == null && unwindHandler == null && handler == null)
						{
							instructionPtr = PerformTCO(instructionPtr, argsCount);
							flags |= CallStackItemFlags.TailCall;
						}
					}
				}
			}



			if (fn.Type == DataType.ClrFunction)
			{
				//IList<DynValue> args = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - argsCount, argsCount, false);
				IList<DynValue> args = CreateArgsListForFunctionCall(argsCount, 0);
				// we expand tuples before callbacks
				// args = DynValue.ExpandArgumentsToList(args);
				SourceRef sref = GetCurrentSourceRef(instructionPtr);

				m_ExecutionStack.Push(new CallStackItem()
				{
					ClrFunction = fn.Callback,
					ReturnAddress = instructionPtr,
					CallingSourceRef = sref,
					BasePointer = -1,
					ErrorHandler = handler,
					Continuation = continuation,
					ErrorHandlerBeforeUnwind = unwindHandler,
					Flags = flags,
				});

				var ret = fn.Callback.Invoke(new ScriptExecutionContext(this, fn.Callback, sref), args, isMethodCall: thisCall);
				m_ValueStack.RemoveLast(argsCount + 1);
				m_ValueStack.Push(ret);

				m_ExecutionStack.Pop();

				return Internal_CheckForTailRequests(null, instructionPtr);
			}
			else if (fn.Type == DataType.Function)
			{
				m_ValueStack.Push(DynValue.NewNumber(argsCount));
				m_ExecutionStack.Push(new CallStackItem()
				{
					BasePointer = m_ValueStack.Count,
					ReturnAddress = instructionPtr,
					Debug_EntryPoint = fn.Function.EntryPointByteCodeLocation,
					CallingSourceRef = GetCurrentSourceRef(instructionPtr),
					ClosureScope = fn.Function.ClosureContext,
					ErrorHandler = handler,
					Continuation = continuation,
					ErrorHandlerBeforeUnwind = unwindHandler,
					Flags = flags,
				});
				return fn.Function.EntryPointByteCodeLocation;
			}

			// fallback to __call metamethod
			var m = GetMetamethod(fn, "__call");

			if (m != null && m.IsNotNil())
			{
				DynValue[] tmp = new DynValue[argsCount + 1];
				for (int i = 0; i < argsCount + 1; i++)
					tmp[i] = m_ValueStack.Pop();

				m_ValueStack.Push(m);

				for (int i = argsCount; i >= 0; i--)
					m_ValueStack.Push(tmp[i]);

				return Internal_ExecCall(argsCount + 1, instructionPtr, handler, continuation);
			}

			throw ScriptRuntimeException.AttemptToCallNonFunc(fn.Type, debugText);
		}
		/// <summary>
		/// Registers a C function as the global name.
		/// </summary>
		/// <param name="state">
		/// A <see cref="IntPtr"/>
		/// </param>
		/// <param name="name">
		/// A <see cref="System.String"/>
		/// </param>
		/// <param name="fn">
		/// A <see cref="CallbackFunction"/>
		/// </param>
		public static void lua_register( IntPtr state, string name, CallbackFunction fn )
		{
			lua_pushcfunction( state, fn );
			lua_setglobal( state, name );
		}
Example #58
0
 public void Query(string index, IndexQuery query, string[] includes, CallbackFunction.Load<QueryResult> callback)
 {
     this.Client.Query(index, query, includes, callback);
 }
        private WorkItem GetWorkItem(CallbackFunction asyncCallback)
        {
            WorkItem workItem;
            if (!returnedWorkItems.TryDequeue(out workItem))
            {
                workItem = new WorkItem();
                workItem.WorkItemStateTypeless = new WorkItemStateTypeless(workItem);
            }

            workItem.SingleThreadRunner = null;
            workItem.IsCompleted = false;
            workItem.Result = null;
            workItem.AsyncCallback = asyncCallback;
            return workItem;
        }
 public void Load(string key, CallbackFunction.Load<KeyValuePair<string, Attachment>> callback)
 {
     Client.AttachmentGet(key, callback);
 }