예제 #1
0
        private void searchResponse(string strResult)
        {
            //in contrast:
            //netc.SendTCPString(remoteIEP, SearchResponseHead + clientLocal.ToString() + GlobalVar.SplitChar_Path + strResult);
            int          locaSplit    = strResult.LastIndexOf(GlobalVar.SplitChar_Path);
            ClientBrief  clientRemote = new ClientBrief(strResult.Substring(0, locaSplit));
            List <TDocs> listResult   = JsonConvert.DeserializeObject <List <TDocs> >(strResult.Substring(locaSplit + 1));

            object[] obj = new object[3];
            obj[0] = clientRemote;
            obj[1] = listResult;
            if (RemoteSearchResponse != null)
            {
                System.ComponentModel.ISynchronizeInvoke aSynch = RemoteSearchResponse.Target as System.ComponentModel.ISynchronizeInvoke;
                if (aSynch.InvokeRequired)
                {
                    MessageEventArgs msarg = new MessageEventArgs(obj);
                    object[]         args  = new object[2] {
                        this, msarg
                    };
                    aSynch.Invoke(RemoteSearchResponse, args);
                }
                else
                {
                    RemoteSearchResponse(this, new MessageEventArgs(obj));
                }
            }
        }
예제 #2
0
        private void OnCollectionWasChanged(
            Action action, DataObject dataObject)
        {
            KeyedCollectionWasChangedEventArgs <DataObject> args =
                new KeyedCollectionWasChangedEventArgs <DataObject>(action, dataObject);
            EventHandler <KeyedCollectionWasChangedEventArgs <DataObject> > handler =
                CollectionWasChanged;

            if (handler != null)
            {
                foreach (EventHandler <KeyedCollectionWasChangedEventArgs <DataObject> > SingleCast
                         in handler.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke syncInvoke =
                        SingleCast.Target as System.ComponentModel.ISynchronizeInvoke;

                    try
                    {
                        if ((syncInvoke != null) && (syncInvoke.InvokeRequired))
                        {
                            syncInvoke.Invoke(SingleCast, new Object[] { this, args });
                        }
                        else
                        {
                            SingleCast(this, args);
                        }
                    }
                    catch
                    { throw; }
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Генерирует событие возникновения ошибок при работе сети.
        /// </summary>
        private void OnNetworkErrorOccurred(NetworkErrorEventArgs args)
        {
            NetworkErrorOccurredEventHandler handler = NetworkErrorOccurred;

            if (args == null)
            {
                args = new NetworkErrorEventArgs();
            }

            if (handler != null)
            {
                foreach (NetworkErrorOccurredEventHandler singleCast in handler.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke syncInvoke =
                        singleCast.Target as System.ComponentModel.ISynchronizeInvoke;

                    if (syncInvoke != null)
                    {
                        if (syncInvoke.InvokeRequired)
                        {
                            syncInvoke.Invoke(singleCast, new Object[] { this, args });
                        }
                        else
                        {
                            singleCast(this, args);
                        }
                    }
                    else
                    {
                        singleCast(this, args);
                    }
                }
            }
            return;
        }
예제 #4
0
        public void BuildIndexThread(object rebuild)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            long[] ret = m_Index.BuildIndex((bool)rebuild);
            watch.Stop();
            if (IndexBuildFinish != null)
            {
                MessageEventArgs arg = new MessageEventArgs();
                arg.MessageObj    = new object[2];
                arg.MessageObj[0] = ret;
                arg.MessageObj[1] = watch.ElapsedMilliseconds;
                //avoid cross thread calling error
                System.ComponentModel.ISynchronizeInvoke aSynch = SearchFinish.Target as System.ComponentModel.ISynchronizeInvoke;
                if (aSynch.InvokeRequired)
                {
                    object[] args = new object[2] {
                        this, arg
                    };
                    aSynch.Invoke(IndexBuildFinish, args);
                }
                else
                {
                    IndexBuildFinish(this, arg);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Method call event event safety - for using event beyond threads
        /// </summary>
        /// <param name="method">event delegate</param>
        /// <param name="args">event arguments - the first one is the calling method like "this"</param>
        public static void Invoke(Delegate method, object[] args)
        {
            if (method != null)
            {
                foreach (Delegate handler in method.GetInvocationList())
                {
                    if (handler.Target is System.Windows.Forms.Control)
                    {
                        System.Windows.Forms.Control target = handler.Target as System.Windows.Forms.Control;

                        if (target.IsHandleCreated)
                        {
                            target.BeginInvoke(handler, args);
                        }
                    }
                    else if (handler.Target is System.ComponentModel.ISynchronizeInvoke)
                    {
                        System.ComponentModel.ISynchronizeInvoke target = handler.Target as System.ComponentModel.ISynchronizeInvoke;
                        target.BeginInvoke(handler, args);
                    }
                    else
                    {
                        handler.DynamicInvoke(args);
                    }
                }
            }
        }
예제 #6
0
파일: ComPort.cs 프로젝트: serialbus/NGK
        /// <summary>
        /// Генерирует событие ошибки при работе com-порта
        /// </summary>
        /// <param name="args">Аргументы события</param>
        private void OnErrorOccurred(ErrorOccurredEventArgs args)
        {
            EventHandlerErrorOccurred handle = ErrorOccurred;

            if (handle != null)
            {
                foreach (EventHandlerErrorOccurred singleCast in handle.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke synckInvoke =
                        singleCast.Target as System.ComponentModel.ISynchronizeInvoke;

                    if (synckInvoke != null)
                    {
                        if (synckInvoke.InvokeRequired == true)
                        {
                            synckInvoke.Invoke(singleCast, new Object[] { this, args });
                        }
                        else
                        {
                            singleCast(this, args);
                        }
                    }
                    else
                    {
                        singleCast(this, args);
                    }
                }
            }
            return;
        }
            public void Spawn2(System.ComponentModel.ISynchronizeInvoke obj)
            {
                var p = new System.Diagnostics.Process();

                p.SynchronizingObject = obj;
                p.Exited += this.Thread2;
            }
예제 #8
0
파일: ComPort.cs 프로젝트: serialbus/NGK
        /// <summary>
        /// Генерирует событие отправки сообщения
        /// </summary>
        /// <param name="args">Аргументы события</param>
        private void OnResponseWasSent(MessageEventArgs args)
        {
            EventHandleResponseWasSent handler = ResponseWasSent;

            if (handler != null)
            {
                foreach (EventHandleResponseWasSent singleCast in handler.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke syncInvoke = singleCast.Target as
                                                                          System.ComponentModel.ISynchronizeInvoke;

                    if (syncInvoke != null)
                    {
                        if (syncInvoke.InvokeRequired)
                        {
                            syncInvoke.Invoke(singleCast, new Object[] { this, args });
                        }
                        else
                        {
                            singleCast(this, args);
                        }
                    }
                    else
                    {
                        singleCast(this, args);
                    }
                }
            }
            return;
        }
예제 #9
0
        /// <summary>
        /// Генерирует событие изменения состояния реле
        /// </summary>
        protected virtual void OnValueWasChanged()
        {
            EventHandler handler = ValueWasChanged;
            EventArgs    args    = new EventArgs();

            if (handler != null)
            {
                foreach (EventHandler singleCast in handler.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke syncInvoke =
                        singleCast.Target as System.ComponentModel.ISynchronizeInvoke;

                    if (syncInvoke != null)
                    {
                        if (syncInvoke.InvokeRequired == true)
                        {
                            syncInvoke.Invoke(singleCast, new object[] { this, args });
                        }
                        else
                        {
                            singleCast(this, args);
                        }
                    }
                }
            }
            return;
        }
예제 #10
0
        ///// <summary>
        /////  ( WPF 适用 ) 延迟指定时间后执行。 在此期间如果再次调用,则重新计时
        ///// </summary>
        ///// <param name="dispatcher"></param>
        //public void Debounce(double interval, Action action, System.Windows.Threading.Dispatcher dispatcher = null)
        //{
        //    lock (this)
        //    {
        //        if (mDebounceTimer == null)
        //        {
        //            mDebounceTimer = new System.Timers.Timer(interval);
        //            mDebounceTimer.AutoReset = false;
        //            mDebounceTimer.Elapsed += (o, e) =>
        //            {
        //                mDebounceTimer.Stop();
        //                mDebounceTimer.Close();
        //                mDebounceTimer = null;

        //                if (dispatcher != null && dispatcher.Thread.IsBackground == false)
        //                {
        //                    dispatcher.Invoke(action, null);
        //                }
        //                else
        //                {
        //                    action.Invoke();
        //                }
        //            };
        //        }
        //        mDebounceTimer.Stop();
        //        mDebounceTimer.Start();
        //    }
        //}

        /// <summary>
        /// ( Winform 适用 ) 延迟指定时间后执行。 在此期间如果再次调用,则重新计时
        /// </summary>
        /// <param name="syncInvoke">同步对象,一般为控件。 如不需同步可传null</param>
        public void Debounce(double interval, Action action, System.ComponentModel.ISynchronizeInvoke syncInvoke)
        {
            lock (this)
            {
                if (mDebounceTimer == null)
                {
                    mDebounceTimer           = new System.Timers.Timer(interval);
                    mDebounceTimer.AutoReset = false;
                    mDebounceTimer.Elapsed  += (o, e) =>
                    {
                        mDebounceTimer.Stop();
                        mDebounceTimer.Close();
                        mDebounceTimer = null;

                        if (syncInvoke != null && syncInvoke.InvokeRequired == true)
                        {
                            syncInvoke.Invoke(action, null);
                        }
                        else
                        {
                            action.Invoke();
                        }
                    };
                }
                mDebounceTimer.Stop();
                mDebounceTimer.Start();
            }
        }
예제 #11
0
        /// <summary>
        /// Генерирует событие изменение списка, удаление, вставка, добавление
        /// элементов списка
        /// </summary>
        private void OnListWasChanged()
        {
            EventHandler handler = ListWasChanged;
            EventArgs    args    = new EventArgs();

            if (handler != null)
            {
                foreach (EventHandler singleCast in handler.GetInvocationList())
                {
                    System.ComponentModel.ISynchronizeInvoke syncInvoke =
                        singleCast.Target as System.ComponentModel.ISynchronizeInvoke;
                    if (syncInvoke != null)
                    {
                        if (syncInvoke.InvokeRequired)
                        {
                            syncInvoke.Invoke(singleCast, new Object[] { this, args });
                        }
                        else
                        {
                            singleCast(this, args);
                        }
                    }
                    else
                    {
                        singleCast(this, args);
                    }
                }
            }
        }
예제 #12
0
 public static void SynchronizedInvoke(this System.ComponentModel.ISynchronizeInvoke sync, Action action)
 {
     if (!sync.InvokeRequired)
     {
         action();
         return;
     }
     sync.Invoke(action, new object[] { });
 }
예제 #13
0
        public bool ExecuteAndWait(string args, System.ComponentModel.ISynchronizeInvoke form)
        {
            bool val = Execute(args, form);

            while (!processCaller.IsDone)
            {
                System.Threading.Thread.Sleep(10);
            }
            return(val);
        }
예제 #14
0
 public AppTimer(double interval = 1000, ElapsedEventHandler elapsed = null, System.ComponentModel.ISynchronizeInvoke threadSyncObject = null, bool start = false)
 {
     timer = new Timer();
     timer.SynchronizingObject = threadSyncObject;
     timer.Interval            = interval;
     timer.Elapsed            += elapsed;
     if (start)
     {
         Start();
     }
 }
예제 #15
0
 public static void InvokeIfRequired(this System.ComponentModel.ISynchronizeInvoke obj, System.Windows.Forms.MethodInvoker action)
 {
     if (obj.InvokeRequired)
     {
         var args = new object[0];
         obj.Invoke(action, args);
     }
     else
     {
         action();
     }
 }
 public Communicator(Game game, Version version, System.ComponentModel.ISynchronizeInvoke synchronize) : base()
 {
     try
     {
         Game        = game;
         Version     = version;
         Synchronize = synchronize;
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #17
0
        //private static DatabaseContext _DBContext = new DatabaseContext();
        //public static DatabaseContext DBContext
        //{
        //	get { return _DBContext; }
        //	private set { _DBContext = value; }
        //}

        public static void BuildHandler(System.ComponentModel.ISynchronizeInvoke synchronizingObject)
        {
            _SynchronizingObject = synchronizingObject;
            if (_Handler != null)
            {
                _Handler.Dispose();
            }

            logger.Info("Building new GuiHandler");

            _Handler = new GuiHandler(_SynchronizingObject,
                                      Commands.IPC_DEFAULT_GUI_CLIENT_NAME, Commands.IPC_DEFAULT_HOST, Commands.IPC_DEFAULT_PORT);
        }
예제 #18
0
 protected void TriggerEvent(Delegate e, params object[] args)
 {
     foreach (Delegate del in e.GetInvocationList())
     {
         System.ComponentModel.ISynchronizeInvoke syncer = del.Target as System.ComponentModel.ISynchronizeInvoke;
         if (syncer == null)
         {
             del.DynamicInvoke(args);
         }
         else
         {
             syncer.BeginInvoke(del, args);
         }
     }
 }
예제 #19
0
        public static bool StartProcessWithCallback(
            string fileName,
            string args,
            System.ComponentModel.ISynchronizeInvoke synchroInvoke,
            EventHandler eventHandler,
            string workingDir       = null,
            StringBuilder stdOutput = null
            )
        {
            Process proc = new Process();

            proc.StartInfo.FileName  = fileName;
            proc.StartInfo.Arguments = args;

            proc.StartInfo.RedirectStandardInput  = false;
            proc.StartInfo.RedirectStandardOutput = (stdOutput != null);
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.CreateNoWindow         = true;

            if (workingDir != null)
            {
                proc.StartInfo.WorkingDirectory = workingDir;
            }
            proc.SynchronizingObject = synchroInvoke;
            proc.EnableRaisingEvents = true;
            proc.Exited += eventHandler;
            try
            {
                proc.Start();

                if (stdOutput != null)
                {
                    string results = proc.StandardOutput.ReadToEnd();
                    proc.WaitForExit();

                    if (results != null &&
                        results.Trim().Length > 0)
                    {
                        stdOutput.Append(results.Trim());
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #20
0
        /// <summary>
        /// Remove all registered assembly object from their lists.
        /// </summary>
        /// <param name="assembly">Assembly where these objects are declared.</param>
        public static void UnregisterAssembly(Assembly assembly)
        {
            try {
                if (assembly == null)
                {
                    return;
                }

                lock (objectsSync) {
                    unregisteringAssembly.Invoke(null, new UnregisteringAssemblyEventArgs(assembly));

                    List <AssemblyObject> removeList = new List <AssemblyObject>();

                    foreach (AssemblyObject obj in objectList)
                    {
                        Debug.Assert(obj.Object.Assembly != null);

                        if (obj.Object.Assembly.FullName == assembly.FullName)
                        {
                            removeList.Add(obj);
                        }
                    }

                    foreach (AssemblyObject obj in removeList)
                    {
                        System.ComponentModel.ISynchronizeInvoke sync = obj.List as System.ComponentModel.ISynchronizeInvoke;

                        if (sync != null && sync.InvokeRequired)
                        {
                            sync.BeginInvoke(new RemoveObjectDelegate(obj.List.Remove), new object[] { obj.Object });
                        }
                        else
                        {
                            obj.List.Remove(obj.Object);
                        }

                        objectList.Remove(obj);
                    }

                    GC.Collect();
                }
            }
            catch (Exception e) {
                string message = String.Format("Error unregistering assembly {0}. Some objects may be still registered and could cause conficts.", assembly.FullName);
                Trace.WriteLine(message + " Exception:\n" + e.ToString(), "Runtime");
                System.Windows.Forms.MessageBox.Show(message, "Waring");
            }
        }
예제 #21
0
 public Project1(System.ComponentModel.ISynchronizeInvoke syncObject) :
     base(syncObject)
 {
     //
     // Global Initialization
     //
     OpenSpan.Diagnostics.Diagnostic.Initialize();
     //
     // Initialize properties
     //
     this.Project1_Initialize();
     //
     // Initialize Runtime
     //
     base.Initialize();
 }
 public OpenSpanArchitecture(System.ComponentModel.ISynchronizeInvoke syncObject) :
     base(syncObject)
 {
     //
     // Initialize properties
     //
     this.mId                    = new OpenSpan.Design.ComponentIdentity("Project-8D2B445854EFE75");
     this.mVersion               = new System.Version("6.2.14.0");
     this.mDeploymentVersion     = "1.0";
     this.mTransformationVersion = new System.Version("5.2.259.6");
     this.mTargetEnvironment     = OpenSpan.Design.TargetEnvironment.Driver;
     //
     // Initialize Runtime
     //
     base.Initialize();
 }
예제 #23
0
 public static void RaiseEventAndExecuteItInTheTargetThread(System.MulticastDelegate _event, object[] _ParamArray_args)
 {
     if ((_event != null))
     {
         if (_event.GetInvocationList().Length > 0)
         {
             System.ComponentModel.ISynchronizeInvoke _sync = null;
             foreach (System.MulticastDelegate _delegate in _event.GetInvocationList())
             {
                 if (((_sync == null) && (typeof(System.ComponentModel.ISynchronizeInvoke).IsAssignableFrom(_delegate.Target.GetType())) && (!_delegate.Target.GetType().IsAbstract)))
                 {
                     try
                     {
                         _sync = (System.ComponentModel.ISynchronizeInvoke)_delegate.Target;
                     }
                     catch (System.Exception ex)
                     {
                         System.Diagnostics.Debug.WriteLine(ex.ToString());
                         _sync = null;
                     }
                 }
                 if (_sync == null)
                 {
                     try
                     {
                         _delegate.DynamicInvoke(_ParamArray_args);
                     }
                     catch (System.Exception ex)
                     {
                         System.Diagnostics.Debug.WriteLine(ex.ToString());
                     }
                 }
                 else
                 {
                     try
                     {
                         _sync.Invoke(_delegate, _ParamArray_args);
                     }
                     catch (System.Exception ex)
                     {
                         System.Diagnostics.Debug.WriteLine(ex.ToString());
                     }
                 }
             }
         }
     }
 }
예제 #24
0
 public bool Execute(string args, System.ComponentModel.ISynchronizeInvoke form)
 {
     try
     {
         processCaller                 = new Process.ProcessCaller(form);
         processCaller.FileName        = Source;
         processCaller.Arguments       = args;
         processCaller.StdErrReceived += new My.Process.DataReceivedHandler(writeStreamInfo);
         processCaller.StdOutReceived += new My.Process.DataReceivedHandler(writeStreamInfo);
         processCaller.Completed      += new EventHandler(processCompletedOrCanceled);
         processCaller.Cancelled      += new EventHandler(processCompletedOrCanceled);
         processCaller.Start();
         return(true);
     }
     catch { }
     return(false);
 }
예제 #25
0
        /// <summary>
        /// 异步请求HTTP POST
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">普通表单项(非二进制)</param>
        /// <param name="byteData">二进制数据(通常指附件)</param>
        /// <param name="byteDataFileNames">二进制数据对应的文件名(通常指附件)</param>
        /// <param name="isGZip">是否压缩数据(只针对二进制而言)</param>
        /// <param name="dataEncoding">发送和读取数据的编码</param>
        /// <param name="timeoutMillisecond">超时时间(单位:毫秒)</param>
        /// <param name="requestCookies">提交的cookie集合</param>
        /// <param name="invokeObject">回调函数的调用对象</param>
        /// <param name="callBackHandle">回调</param>
        /// <param name="evData">回调附加的传递参数</param>
        /// <returns></returns>
        public static HttpWebRequest AsynPost(string url, IDictionary <string, string> data
                                              , IDictionary <string, byte[]> byteData, IDictionary <string, string> byteDataFileNames, bool isGZip, Encoding dataEncoding, int timeoutMillisecond
                                              , CookieCollection requestCookies
                                              , System.ComponentModel.ISynchronizeInvoke invokeObject, HttpAccessAsynCallBack callBackHandle, Object evData)
        {
            HttpWebRequest request = GetHttpPostRequest(url, data, byteData, byteDataFileNames, isGZip, dataEncoding, timeoutMillisecond, requestCookies);

            System.Collections.ArrayList poD = new System.Collections.ArrayList();
            poD.Add(request);
            poD.Add(invokeObject);
            poD.Add(callBackHandle);

            System.Threading.WaitCallback edGetResponseCallB = new System.Threading.WaitCallback(delegate(object poData) {
                System.Collections.ArrayList pD = (System.Collections.ArrayList)poData;
                HttpWebRequest req = (HttpWebRequest)pD[0];
                System.ComponentModel.ISynchronizeInvoke invObj = (System.ComponentModel.ISynchronizeInvoke)pD[1];
                HttpAccessAsynCallBack callB = (HttpAccessAsynCallBack)pD[2];

                HttpWebResponse response = null;
                try {
                    response = (HttpWebResponse)req.GetResponse();
                } catch (Exception ex) {
                    //如果强制被取消的话,就抛错.所以错了就不调用了
                    invObj.Invoke(callB
                                  , new Object[] {
                        null
                        , null
                        , ex
                        , evData
                    });
                    return;
                }
                invObj.Invoke(callB
                              , new Object[] {
                    response
                    , GetCookiesByHeaderSetCookie(response)
                    , null
                    , evData
                });
            });

            System.Threading.ThreadPool.QueueUserWorkItem(edGetResponseCallB, poD);

            return(request);
        }
예제 #26
0
        public void SearchIndexThread(object obj)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            SearchObj sobj = obj as SearchObj;

            if (sobj == null)
            {
                return;
            }
            List <TDocs> listResult = new List <TDocs>();

            try
            {
                listResult = m_Index.Search(sobj.StrQuery);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            watch.Stop();
            if (SearchFinish != null)
            {
                MessageEventArgs arg = new MessageEventArgs();
                arg.MessageObj    = new object[3];
                arg.MessageObj[0] = listResult;
                arg.MessageObj[1] = watch.ElapsedMilliseconds;
                arg.MessageObj[2] = sobj;
                System.ComponentModel.ISynchronizeInvoke aSynch = SearchFinish.Target as System.ComponentModel.ISynchronizeInvoke;
                if (aSynch.InvokeRequired)
                {
                    object[] args = new object[2] {
                        this, arg
                    };
                    aSynch.Invoke(SearchFinish, args);
                }
                else
                {
                    SearchFinish(this, arg);
                }
            }
        }
예제 #27
0
        private void InvokeDelegate(Delegate del, object[] args)
        {
            System.ComponentModel.ISynchronizeInvoke synchronizer = del.Target as System.ComponentModel.ISynchronizeInvoke;

            if (synchronizer != null)
            {
                if (synchronizer.InvokeRequired == false)
                {
                    del.DynamicInvoke(args);
                    return;
                }
                try {
                    synchronizer.Invoke(del, args);
                } catch { }
            }
            else
            {
                del.DynamicInvoke(args);
            }
        }
예제 #28
0
        /// <summary>
        /// Calls a method using the objects invokable object.
        /// </summary>
        /// <param name="method">The method to call.</param>
        /// <param name="args">The arguments to call the object with.</param>
        /// <returns>The result returned from method, or null if the method
        /// could not be invoked.</returns>
        protected object Invoke(Delegate method, params object[] args)
        {
            System.ComponentModel.ISynchronizeInvoke invokeable = GetInvokeObject();

            try
            {
                if (invokeable != null)
                {
                    return(invokeable.Invoke(method, args));
                }

                if (mAllowMultithreadedCallbacks)
                {
                    return(method.DynamicInvoke(args));
                }
            }
            catch { }

            return(null);
        }
예제 #29
0
 public Game(System.ComponentModel.ISynchronizeInvoke si, string setupfilename) : base()
 {
     try
     {
         Random        = new System.Random();
         FileVersion   = new Version(FILEVERSION_MAJOR, FILEVERSION_MINOR);
         StockIndexes  = new StockIndexes();
         Stocks        = new Stocks();
         Players       = new Players();
         Configuration = new Configuration(setupfilename, Random, StockIndexes, Stocks, Players);
         if (StockIndexes == null)
         {
             StockIndexes = Configuration.StockIndexes;
         }
         if (Stocks == null)
         {
             Stocks = Configuration.Stocks;
         }
         if (Players == null)
         {
             Players = Configuration.Players;
         }
         MarketState   = new MarketState();
         CurrentPlayer = new Player(Players.NextPlayerId, String.Empty, String.Empty, Stocks, false, true);
         Players.Add(CurrentPlayer);
         SynchronizeRoot               = Singleton.Instance;
         PlayTimer                     = new System.Timers.Timer(PLAY_TIMER_INTERVAL);
         PlayTimer.AutoReset           = true;
         PlayTimer.Elapsed            += new System.Timers.ElapsedEventHandler(PlayTimerElapsed);
         PlayTimer.SynchronizingObject = si;
         while (!PlayTimer.Enabled)
         {
             PlayTimer.Start();
         }
         Disposed = false;
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
예제 #30
0
        ///// <summary>
        /////  ( WPF适用 ) 即刻执行,执行之后,在指定时间内再次调用无效
        ///// </summary>
        ///// <param name="interval">不应期,这段时间内调用无效</param>
        ///// <param name="dispatcher">同步对象,一般为控件。 如不需同步可传null</param>
        //public void Throttle(double interval, Action action, System.Windows.Threading.Dispatcher dispatcher = null)
        //{
        //    System.Threading.Monitor.Enter(this);
        //    bool needExit = true;
        //    try
        //    {
        //        if (mThrottleTimer == null)
        //        {
        //            mThrottleTimer = new System.Timers.Timer(interval);
        //            mThrottleTimer.AutoReset = false;
        //            mThrottleTimer.Elapsed += (o, e) =>
        //            {
        //                mThrottleTimer.Stop();
        //                mThrottleTimer.Close();
        //                mThrottleTimer = null;
        //            };
        //            mThrottleTimer.Start();

        //            System.Threading.Monitor.Exit(this); // 已保证Timer成功创建, 可以将锁释放
        //            needExit = false;

        //            if (dispatcher != null && dispatcher.Thread.IsBackground == false) //这个过程不能锁
        //            {
        //                dispatcher.Invoke(action, null);
        //            }
        //            else
        //            {
        //                action();
        //            }
        //        }
        //    }
        //    finally
        //    {
        //        if (needExit)
        //        {
        //            System.Threading.Monitor.Exit(this);
        //        }
        //    }
        //}

        /// <summary>
        /// ( Winform 适用 ) 即刻执行,执行之后,在指定时间内再次调用无效
        /// </summary>
        /// <param name="syncInvoke">同步对象,一般为控件。 如不需同步可传null</param>
        public void Throttle(double interval, Action action, System.ComponentModel.ISynchronizeInvoke syncInvoke)
        {
            System.Threading.Monitor.Enter(this);
            bool needExit = true;

            try
            {
                if (mThrottleTimer == null)
                {
                    mThrottleTimer           = new System.Timers.Timer(interval);
                    mThrottleTimer.AutoReset = false;
                    mThrottleTimer.Elapsed  += (o, e) =>
                    {
                        mThrottleTimer.Stop();
                        mThrottleTimer.Close();
                        mThrottleTimer = null;
                    };

                    mThrottleTimer.Start();

                    System.Threading.Monitor.Exit(this); // 已保证Timer成功创建, 可以将锁释放
                    needExit = false;

                    if (syncInvoke != null && syncInvoke.InvokeRequired == true) //这个过程不能锁
                    {
                        syncInvoke.Invoke(action, null);
                    }
                    else
                    {
                        action();
                    }
                }
            }
            finally
            {
                if (needExit)
                {
                    System.Threading.Monitor.Exit(this);
                }
            }
        }
예제 #31
0
 internal void InheritInvokeOptions(DNSService fromService)
 {
     AllowApplicationForms = fromService.AllowApplicationForms;
     InvokeableObject = fromService.InvokeableObject;
     AllowMultithreadedCallbacks = fromService.AllowMultithreadedCallbacks;
 }
예제 #32
0
        public void StartTimer(bool customStart, DateTime start, System.ComponentModel.ISynchronizeInvoke s)
        {
            if (_active)
            {
                Log("Attempt to start timer that is already running." + Environment.NewLine);
                return;
            }
            if (_inLink.AuthStatus != AuthStatusType.AS_OK)
            {
                Log("Not yet authorized." + Environment.NewLine);
                return;
            }

            if (_interval < 120000)
            {
                Log("Interval too short, needs to be at least 2 minutes" + Environment.NewLine);
                return;
            }

            _timer.Interval = _interval;
            _timer.SynchronizingObject = s;
            _syncObj = s;
            _timer.Elapsed += new ElapsedEventHandler(DoUpdate);
            _timer.Enabled = true;
            _active = true;

            if (customStart)
            {
                _lastUpdate = start;
                Log(_sitePrefix + "Starting auto-transfer at " + DateTime.Now.ToString() + Environment.NewLine +
                    "Starting from custom date/time: " + start.ToString() + Environment.NewLine +
                    "Running update function to clear back-log" + Environment.NewLine);

                DoUpdate(this, null);
            }
            else
            {
                TradeHistory t;

                try
                {
                    t = _inLink.GetTradeHistory();
                    _lastUpdate = t.orders[t.orders.Count - 1].dateTime;
                    Log(_sitePrefix + "Starting auto-transfer at " + DateTime.Now.ToString() + Environment.NewLine
                        + _sitePrefix + "Most recent entry in trade history at " + _lastUpdate.ToString() + " (server time)" + Environment.NewLine);
                }
                catch (BTCTException ex)
                {
                    Log(_sitePrefix + "Error obtaining initial trade history - Timer aborted. Message: " + ex.Message + Environment.NewLine);
                    StopTimer();
                    return;
                }
            }
        }
예제 #33
0
        internal void Initialize(string appPath, System.ComponentModel.ISynchronizeInvoke synchronizingObject)
        {
            this.appPath = appPath;
            this.synchronizingObject = synchronizingObject;

            this.historyFolder = Growl.CoreLibrary.PathUtility.Combine(Utility.UserSettingFolder, @"History\");
            PastNotificationManager.HistoryFolder = this.historyFolder;

            string imageCacheFolder = Growl.CoreLibrary.PathUtility.Combine(Utility.UserSettingFolder, @"ImageCache\");
            ImageCache.CacheFolder = imageCacheFolder;

            // handle any upgrade logic
            bool upgrade = (Growl.Properties.Settings.Default.SettingsVersion < 2);
            if (upgrade)
            {
                Utility.WriteDebugInfo("UPGRADE INITIATED");

                SettingSaver raSettingSaver = new SettingSaver(REGISTERED_APPLICATIONS_SETTINGS_FILENAME, LegacyDeserializers.LegacyDeserializationHelper.OldApplicationsHelper);
                raSettingSaver.Save(raSettingSaver.Load());

                SettingSaver fcSettingSaver = new SettingSaver(FORWARD_COMPUTERS_SETTINGS_FILENAME, LegacyDeserializers.LegacyDeserializationHelper.OldForwardDestinationHelper);
                fcSettingSaver.Save(fcSettingSaver.Load());

                SettingSaver sbSettingSaver = new SettingSaver(SUBSCRIPTIONS_SETTINGS_FILENAME, LegacyDeserializers.LegacyDeserializationHelper.OldSubscriptionHelper);
                sbSettingSaver.Save(sbSettingSaver.Load());

                PastNotificationManager.DeleteHistory();

                Growl.Properties.Settings.Default.SettingsVersion = 2;

                Utility.WriteDebugInfo(String.Format("UPGRADE COMPLETED - NOW AT VERSION: {0}", Growl.Properties.Settings.Default.SettingsVersion));
            }

            DisplayStyleManager.DisplayLoaded += new DisplayStyleManager.DisplayLoadedEventHandler(DisplayStyleManager_DisplayLoaded);

            LoadPasswords();
            LoadMiscPrefs();
            LoadDisplays();     // this could take a long time as well, but other things depend on it so we have to do it synchronously and just wait
            LoadApplications();
            LoadForwardedComputers();
            LoadSubscriptions();

            // this must come *after* LoadForwardedComputers has ran
            StartBonjour();

            this.activityMonitor = new ActivityMonitor();
            this.activityMonitor.WentIdle += new ActivityMonitor.ActivityMonitorEventHandler(activityMonitor_WentIdle);
            this.activityMonitor.ResumedActivity += new ActivityMonitor.ActivityMonitorEventHandler(activityMonitor_ResumedActivity);
            this.activityMonitor.StillActive += new EventHandler(activityMonitor_StillActive);
            this.activityMonitor.CheckForIdle = Properties.Settings.Default.CheckForIdle;
            this.activityMonitor.IdleAfterSeconds = Properties.Settings.Default.IdleAfterSeconds;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SrCslgStorageSystemScanAction"/> class.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="hostname">The hostname.</param>
 /// <param name="username">The username.</param>
 /// <param name="passwordSecret">The password secret.</param>
 public SrCslgStorageSystemScanAction(System.ComponentModel.ISynchronizeInvoke invoker, IXenConnection connection, List<StorageLinkConnection> storageLinkConnections, string hostname, string username, string passwordSecret)
     : base(connection, hostname, username, passwordSecret)
 {
     _SLConnections = storageLinkConnections;
     _invoker = invoker;
 }
예제 #35
0
파일: Util.cs 프로젝트: CodeAsm/open-sauce
			/// <summary>
			/// Initializes an AsyncOperation with an association to the
			/// supplied ISynchronizeInvoke.  All events raised from this
			/// object will be delivered via this target.  (This might be a
			/// Control object, so events would be delivered to that Control's
			/// UI thread.)
			/// </summary>
			/// <param name="target">An object implementing the
			/// ISynchronizeInvoke interface.  All events will be delivered
			/// through this target, ensuring that they are delivered to the
			/// correct thread.</param>
			public AsyncOperation(System.ComponentModel.ISynchronizeInvoke target)
			{
				this.target = target;
				isRunning = false;
			}
        internal void InheritInvokeOptions(DNSService fromService)
        {
            // We set the MultiThreadedCallback property first,
            // as it has the potential to affect the other properties.
            AllowMultithreadedCallbacks = fromService.AllowMultithreadedCallbacks;

            AllowApplicationForms = fromService.AllowApplicationForms;
            InvokeableObject = fromService.InvokeableObject;
        }