Ejemplo n.º 1
0
        /// <summary>
        /// starts thread with target if any
        /// </summary>
        protected void StartTarget()
        {
            Exception exceptn       = null;
            bool      bHadException = false;

            try
            {
                bThreadIsAborting = false;
                if (ThreadStart != null)
                {
                    ThreadStart.Invoke();
                }
                else if (ParamterizedStart != null)
                {
                    ParamterizedStart.Invoke(_arg);
                }
            }
            catch (Exception ex)
            {
                bHadException       = true;
                exceptn             = ex;
                this._lastException = ex;
                OnThreadException(ex);
            }
            finally
            {
                OnThreadCompleted(bHadException, exceptn);
            }
        }
Ejemplo n.º 2
0
 public static void SafeInvoke(this ParameterizedThreadStart method, object obj)
 {
     if (method != null)
     {
         method.Invoke(obj);
     }
 }
Ejemplo n.º 3
0
        void RunWatcher()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry((Dns.GetHostName()));

            if (hostEntry.AddressList.Length > 0)
            {
                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        Sniffer s = new Sniffer();
                        foreach (TcpSnifferPort port in this.TcpSnifferPorts)
                        {
                            if (port.IPAddress == null || (port.IPAddress != null && port.IPAddress.Equals(ip)))
                            {
                                if (port.HandlesReceived)
                                {
                                    s.IpPacketReceived += port.Received;
                                }
                                if (port.HandlesSent)
                                {
                                    s.IpPacketSent += port.Sent;
                                }
                            }
                        }
                        ParameterizedThreadStart pts = new ParameterizedThreadStart(s.WatchAddress);
                        pts.Invoke(ip);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// starts thread with target if any
        /// </summary>
        private void StartTarget()
        {
            Exception exceptn       = null;
            var       bHadException = false;

            try
            {
                if (_ts != null)
                {
                    _ts.Invoke();
                }
                else if (_pts != null)
                {
                    _pts.Invoke(ThreadStartArg);
                }
            }
            catch (Exception ex)
            {
                bHadException      = true;
                exceptn            = ex;
                this.LastException = ex;
                OnThreadException(ex);
            }
            finally
            {
                OnThreadCompleted(bHadException, exceptn);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Wrap the start method for the aggregated Thread.  This method uses the "thread catalog"
        /// to keep track of which threads are running.  It also insures that any Exception that
        /// occurs in the start method will be caught and reported.
        /// </summary>
        /// <param name="arg"></param>
        private void WrappedParameterizedStart(object arg)
        {
            lock ( mRunning )
            {
                mRunning.Add(this);
            }

            try
            {
                mParameterizedStart.Invoke(arg);
                Finished();
            }
            catch (Exception ex)
            {
                string name    = string.IsNullOrEmpty(mThread.Name) ? "Unnamed" : mThread.Name;
                string message = string.Format("Error in thread {0}:{1}", name, ex.Message);
                // DON'T throw this!  Since this is the start method of a thread there isn't
                // anything to catch it...
                //throw new ApplicationException( message, ex );
                Debug.Print("{0}\n{1}\n", message, ex.StackTrace);
            }

            lock ( mRunning )
            {
                mRunning.Remove(this);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// starts thread with target if any
        /// </summary>
        protected void startTarget()
        {
            Exception exceptn       = null;
            bool      bHadException = false;

            try
            {
                bThreadIsAborting = false;
                if (_Ts != null)
                {
                    _Ts.Invoke();
                }
                else if (_Pts != null)
                {
                    _Pts.Invoke(ThreadStartArg);
                }
            }
            catch (Exception ex)
            {
                bHadException = true;
                exceptn       = ex;
                //this._lastException = ex;
                this.LastException = ex;
                OnThreadException(ex);
            }
            finally
            {
                OnThreadCompleted(bHadException, exceptn);
            }
        }
Ejemplo n.º 7
0
 public void ExecuteAsyncOperation(object param)
 {
     lock (_opLock)
     {
         try
         {
             _start.Invoke(param);
             if (_successCallback != null)
             {
                 _successCallback.Invoke(null);
             }
         }
         catch (Exception ex)
         {
             SdkSettings.Instance.Logger.Log(TraceLevel.Error, ex.Message);
             if (_handler != null)
             {
                 _handler.Show(ex.Message);
             }
             if (_errorCallback != null)
             {
                 _errorCallback.Invoke(null);
             }
         }
         finally
         {
             ;
         }
     }
 }
Ejemplo n.º 8
0
        /// <summary>Downloads bytes from the specified URL and saves them to a file.</summary>
        /// <param name="url">The URL.</param>
        /// <param name="file">The file name.</param>
        /// <param name="days">If the file already exists and was modified during the last so and so days, the download will be bypassed.</param>
        /// <param name="callback">The function to execute once the data has been saved to the file, or a null reference. The argument in the callback function is of type System.String and contains the file name.</param>
        internal static void DownloadAndSaveAsynchronous(string url, string file, double days, ParameterizedThreadStart callback)
        {
            bool download;

            if (File.Exists(file))
            {
                try {
                    DateTime lastWrite = File.GetLastWriteTime(file);
                    TimeSpan span      = DateTime.Now - lastWrite;
                    download = span.TotalDays > days;
                } catch {
                    download = true;
                }
            }
            else
            {
                download = true;
            }
            if (download)
            {
                ThreadStart start = new ThreadStart(
                    () => {
                    try {
                        byte[] bytes     = DownloadBytesFromUrl(url);
                        string directory = Path.GetDirectoryName(file);
                        try {
                            Directory.CreateDirectory(directory);
                            File.WriteAllBytes(file, bytes);
                        } catch (Exception ex) {
                            Debug.AddMessage(Debug.MessageType.Warning, false, "Error writing file " + file + ": " + ex.Message);
                        }
                        if (callback != null)
                        {
                            callback.Invoke(file);
                        }
                    } catch { }
                }
                    );
                Thread thread = new Thread(start);
                thread.IsBackground = true;
                thread.Start();
            }
            else if (callback != null)
            {
                callback.Invoke(file);
            }
        }
Ejemplo n.º 9
0
        public void ThreadCallBack(ParameterizedThreadStart pts, Action action, params int[] ii)
        {
            ParameterizedThreadStart st = new ParameterizedThreadStart(x =>
            {
                pts.Invoke(x);
                action.Invoke();
            });
            Thread thread = new Thread(st);

            thread.Start(ii[0]);
        }
Ejemplo n.º 10
0
 public static void SafeInvoke(this ParameterizedThreadStart method, object obj, Action alternative)
 {
     if (method != null)
     {
         method.Invoke(obj);
     }
     else
     {
         SafeInvoke(alternative);
     }
 }
        public IHttpActionResult Mutex()
        {
            ParameterizedThreadStart pt = (x) =>
            {
            };

            pt.Invoke(DateTime.Now);
            Mutex mutex = new Threading.Mutex();

            return(Json(mutex));
        }
Ejemplo n.º 12
0
 public virtual void Execute()
 {
     if (ThreadStart != null)
     {
         ThreadStart.Invoke();
     }
     else
     {
         ParameterizedThreadStart.Invoke(Obj);
     }
 }
Ejemplo n.º 13
0
        public string ThreadCallBack(ParameterizedThreadStart pts, Func <string> func, params int[] ii)
        {
            string s = string.Empty;
            ParameterizedThreadStart st = new ParameterizedThreadStart(x =>
            {
                pts.Invoke(x);
                s = func.Invoke();
            });
            Thread thread = new Thread(st);

            thread.Start(ii[0]);
            return(s);
        }
Ejemplo n.º 14
0
 /// <summary>Downloads bytes from the specified URL and saves them to a file.</summary>
 /// <param name="url">The URL.</param>
 /// <param name="file">The file name.</param>
 /// <param name="days">If the file already exists and was modified during the last so and so days, the download will be bypassed.</param>
 /// <param name="callback">The function to execute once the data has been saved to the file, or a null reference. The argument in the callback function is of type System.String and contains the file name.</param>
 internal static void DownloadAndSaveAsynchronous(string url, string file, double days, ParameterizedThreadStart callback)
 {
     bool download;
     if (File.Exists(file)) {
         try {
             DateTime lastWrite = File.GetLastWriteTime(file);
             TimeSpan span = DateTime.Now - lastWrite;
             download = span.TotalDays > days;
         } catch {
             download = true;
         }
     } else {
         download = true;
     }
     if (download) {
         ThreadStart start = new ThreadStart(
             () => {
                 try {
                     byte[] bytes = DownloadBytesFromUrl(url);
                     string directory = Path.GetDirectoryName(file);
                     try {
                         Directory.CreateDirectory(directory);
                         File.WriteAllBytes(file, bytes);
                     } catch { }
                     if (callback != null) {
                         callback.Invoke(file);
                     }
                 } catch { }
             }
         );
         Thread thread = new Thread(start);
         thread.IsBackground = true;
         thread.Start();
     } else if (callback != null) {
         callback.Invoke(file);
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Adapts the html source returned by the XWiki server and makes it usable by Word using a local html file.
        /// </summary>
        /// <param name="xmlDoc">A reference to the xml dom.</param>
        public void Filter(ref XmlDocument xmlDoc)
        {
            XmlNodeList images = xmlDoc.GetElementsByTagName("img");

            foreach (XmlNode node in images)
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    XmlAttribute vshapesAttr = node.Attributes["v:shapes"];
                    if (vshapesAttr != null)
                    {
                        node.Attributes.Remove(vshapesAttr);
                    }
                    //remove parameters from URLs
                    String src = node.Attributes["src"].Value.Split('?')[0];
                    //Creating an additional attribute to help identifing the image in the html.
                    XmlAttribute attr = xmlDoc.CreateAttribute(ImageInfo.XWORD_IMG_ATTRIBUTE);
                    //Adding the attribute to the xhtml code.
                    Guid imgId = Guid.NewGuid();
                    attr.Value = imgId.ToString();
                    node.Attributes.Append(attr);
                    //Adding the image to the current image list.
                    ImageInfo imgInfo = new ImageInfo();
                    imgInfo.imgWebSrc = src;
                    if (node.Attributes["alt"] != null)
                    {
                        imgInfo.altText = node.Attributes["alt"].Value;
                    }
                    manager.States.Images.Add(imgId, imgInfo);
                    //Downloading image
                    if (src == "")
                    {
                        continue;
                    }
                    if (src[0] == '/')
                    {
                        src = serverURL + src;
                    }
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(DownloadImage);
                    String folder = localFolder + "\\" + localFilename + manager.AddinSettings.MetaDataFolderSuffix;
                    Object param  = new ImageDownloadInfo(src, folder, imgInfo);
                    pts.Invoke(param);
                    src = folder + "\\" + Path.GetFileName(src);
                    src = "file:///" + src.Replace("\\", "/");
                    node.Attributes["src"].Value = src;
                }
            }
        }
Ejemplo n.º 16
0
        void RunWatcher()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry((Dns.GetHostName()));

            if (hostEntry.AddressList.Length > 0)
            {
                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ParameterizedThreadStart pts = new ParameterizedThreadStart(WatchAddress);
                        pts.Invoke(ip);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        internal void HandleItem()
        {
            // Set start state
            m_startTime = DateTime.UtcNow.Ticks;
            m_status    = ThreadStatus.Executing;

            try
            {
                // Invoke the user's call back function
                if ((object)m_ctx == null)
                {
                    if ((object)m_tsCallback != null)
                    {
                        m_tsCallback.Invoke();
                    }
                    else if ((object)m_ptsCallback != null)
                    {
                        m_ptsCallback.Invoke(m_state);
                    }
                    else
                    {
                        m_ctxCallback.Invoke(m_state);
                    }
                }
#if !MONO
                else
                {
                    // If user specified an alternate execution context, we invoke
                    // their delegate under that context
                    ExecutionContext.Run(m_ctx, m_ctxCallback, m_state);
                }
#endif
            }
            finally
            {
                // Set finish state
                if (m_status == ThreadStatus.Executing)
                {
                    m_status = ThreadStatus.Completed;
                }
                m_stopTime = DateTime.UtcNow.Ticks;

                ManagedThreads.Remove(this);
            }
        }
Ejemplo n.º 18
0
        public static Thread RunTask(ParameterizedThreadStart task, params object[] parameters)
        {
            if (_semaphore == null)
            {
                if (MaxThreads == 0)
                {
                    MaxThreads = 10;
                }

                _semaphore = new Semaphore(MaxThreads, MaxThreads);
            }

            _semaphore.WaitOne();

            var t = new Thread(delegate()
            {
                try
                {
                    task.Invoke(parameters);
                }
                finally
                {
                    _semaphore.Release();

                    //Remove thread from _thread list
                    lock (_threads)
                    {
                        if (_threads.Contains(Thread.CurrentThread))
                        {
                            _threads.Remove(Thread.CurrentThread);
                        }
                    }
                }
            });

            t.IsBackground = true;

            lock (_threads)
                _threads.Add(t);

            t.Start();

            return(t);
        }
Ejemplo n.º 19
0
        private void OngoingThreadMethod()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        //user can set new data (Method Join() and Start() not block Thread)
                        _userTreadJoinStartCotrol.Set();

                        //wait for incoming user command to Start
                        _threadStartCotrol.WaitOne();

                        if (_userMethod != null)
                        {
                            _userMethod.Invoke();
                        }
                        else
                        {
                            _parameterizedUserMethod.Invoke(_userData);
                        }
                    }
                    catch (Exception exception)
                    {
                        ThreadException = exception;
                    }
                }
            }
            catch
            {
                //ignore
            }
            finally
            {
                //prevention of nullification of a newly created Thread
                if (_thread != null && _thread.Name == Thread.CurrentThread.Name)
                {
                    _thread = null;
                    _userTreadJoinStartCotrol.Reset();
                    _threadStartCotrol.Reset();
                }
            }
        }
Ejemplo n.º 20
0
        public InputPin(int Number, PinParameters.EdgeEvent EdgeEvent = PinParameters.EdgeEvent.none)
        {
            if ((!PinUsage.InputPins.Contains(Number)) & (!PinUsage.OutputPins.Contains(Number)))
            {
                _mode      = PinParameters.Mode.Discrete;
                _number    = Number;
                _direction = PinParameters.Direction.In;

                PinUsage.InputPins.Add(Number);

                var num_str    = Number.ToString();
                var exportPath = @"/sys/class/gpio/export";
                File.WriteAllText(exportPath, num_str);

                _directory = Directory.GetDirectories(@"/sys/class/gpio/", @"gpio" + Number + "*").FirstOrDefault <string>();

                File.WriteAllText(_directory + @"/direction", @"in");

                //инициализируем прерывание
                if (EdgeEvent != PinParameters.EdgeEvent.none)
                {
                    try
                    {
                        _tokenSource = new CancellationTokenSource();

                        File.WriteAllText(_directory + "/edge", EdgeEvent.ToString());

                        var interrupt = new ParameterizedThreadStart(InterruptTask);
                        interrupt.Invoke(new { token = _tokenSource.Token, directory = _directory, pinEvent = this.PinEvent });
                    }
                    catch
                    {
                        throw new Exception("Pin doesn't allow hardaware interrupts");
                    }
                }
            }
            else
            {
                throw new Exception("Pin is used");
            }
        }
        public static Thread RunTask(ParameterizedThreadStart task, params object[] parameters)
        {
            if (_semaphore == null)
            {
                if (MaxThreads == 0)
                    MaxThreads = 10;

                _semaphore = new Semaphore(MaxThreads, MaxThreads);
            }

            _semaphore.WaitOne();

            var t = new Thread(delegate()
            {
                try
                {
                    task.Invoke(parameters);
                }
                finally
                {
                    _semaphore.Release();

                    //Remove thread from _thread list
                    lock (_threads)
                    {
                        if (_threads.Contains(Thread.CurrentThread))
                            _threads.Remove(Thread.CurrentThread);
                    }
                }
            });
            t.IsBackground = true;

            lock (_threads)
                _threads.Add(t);

            t.Start();

            return t;
        }
Ejemplo n.º 22
0
 private void main(object param)
 {
     try
     {
         if (real1 != null)
         {
             real1.Invoke(param);
         }
         real2.Invoke();
     }
     catch (System.Exception ex)
     {
         Console.WriteLine("Undandled exception on thread " + thread.Name);
         Console.WriteLine(ex);
     }
     finally
     {
         lock (syncRoot)
         {
             runningCounter--;
         }
     }
 }
Ejemplo n.º 23
0
 public WpfThread(ParameterizedThreadStart parameterizedThreadStart)
 {
     BackgroundThread = new System.Threading.Thread(x => CatchForAction.ExceptionToUiThread("WpfThreadPool Error", () => parameterizedThreadStart.Invoke(x)))
     {
         IsBackground = true
     };
 }
Ejemplo n.º 24
0
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        #endregion
        //-------------------------------------------------------------------------------
        // This wraps the execution of a tasks delegate in a call to allow extra functionality.
        /// <summary>
        /// Thread process for running tasks.
        /// </summary>
        /// <param name="threadInfo">upon creation.</param>
        //-------------------------------------------------------------------------------
        #region ThreadProc
        private void ThreadProcess(object threadInfo)
        {
            ThreadData threadData = threadInfo as ThreadData;

            while (true)
            {
                int        nTaskCount;
                QueueEntry queueEntry;

                m_queueLock.TryEnterUpgradeableReadLock(5);

                if (m_taskQueue.Count > 0)
                {
                    m_queueLock.EnterWriteLock();
                    queueEntry = m_taskQueue.Dequeue();
                    m_queueLock.ExitWriteLock();
                }
                else
                {
                    queueEntry = null;
                }

                m_queueLock.ExitUpgradeableReadLock();

                if (queueEntry != null)
                {
                    TaskType taskType = queueEntry.TaskType;
                    ParameterizedThreadStart taskDelegate = taskType.TaskOp;

                    Debug.Assert(taskDelegate != null);

                    threadData.NumberOfTasks++;

                    taskType.ExecutingThread = Thread.CurrentThread;

                    Console.WriteLine("processing " + taskType.Name + " on " + Thread.CurrentThread.Name);

                    taskDelegate.Invoke(taskType);

                    Console.WriteLine("finished processing " + taskType.Name + " on " + Thread.CurrentThread.Name);

                    if (taskType.Event != null && !taskType.ContinuousExecution)
                    {
                        taskType.Event.Set();
                    }
                    else
                    {
                        Type type = taskType.GetType();

                        PropertyInfo property   = type.GetProperty("ReturnData");
                        MethodInfo   methodInfo = property.GetGetMethod();


                        taskType.FireCompletedEvent(methodInfo.Invoke(taskType, null));

                        //This allows the task to be continuously executed.
                        if (taskType.ContinuousExecution)
                        {
                            ExecuteTask(taskType.Handle);
                        }
                        else
                        {
                            DestroyTask(taskType.Handle);
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
 public override void Start(object parameter)
 {
     _parameterizedThreadStart.Invoke(parameter);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Import data from access
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ImportDataFromAccessToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (!SystemManager.MONO_MODE)
     {
         //MONO not support this function
         OpenFileDialog AccessFile = new OpenFileDialog();
         AccessFile.Filter = MongoDBHelper.MdbFilter;
         if (AccessFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             MongoDBHelper.ImportAccessPara parm = new MongoDBHelper.ImportAccessPara();
             parm.accessFileName = AccessFile.FileName;
             parm.currentTreeNode = trvsrvlst.SelectedNode;
             parm.strSvrPathWithTag = SystemManager.SelectObjectTag;
             ParameterizedThreadStart Parmthread = new ParameterizedThreadStart(MongoDBHelper.ImportAccessDataBase);
             Thread t = new Thread(Parmthread);
             Parmthread.Invoke(parm);
         }
     }
 }
 /// <summary>
 /// Adapts the html source returned by the XWiki server and makes it usable by Word using a local html file.
 /// </summary>
 /// <param name="xmlDoc">A reference to the xml dom.</param>
 public void Filter(ref XmlDocument xmlDoc)
 {
     XmlNodeList images = xmlDoc.GetElementsByTagName("img");
     foreach (XmlNode node in images)
     {
         if (node.NodeType == XmlNodeType.Element)
         {
             XmlAttribute vshapesAttr = node.Attributes["v:shapes"];
             if (vshapesAttr != null)
             {
                 node.Attributes.Remove(vshapesAttr);
             }
             //remove parameters from URLs
             String src = node.Attributes["src"].Value.Split('?')[0];
             //Creating an additional attribute to help identifing the image in the html.
             XmlAttribute attr = xmlDoc.CreateAttribute(ImageInfo.XWORD_IMG_ATTRIBUTE);
             //Adding the attribute to the xhtml code.
             Guid imgId = Guid.NewGuid();
             attr.Value = imgId.ToString();
             node.Attributes.Append(attr);
             //Adding the image to the current image list.
             ImageInfo imgInfo = new ImageInfo();
             imgInfo.imgWebSrc = src;
             if (node.Attributes["alt"] != null)
             {
                 imgInfo.altText = node.Attributes["alt"].Value;
             }
             manager.States.Images.Add(imgId, imgInfo);
             //Downloading image
             if (src == "") continue;
             if (src[0] == '/')
             {
                 src = serverURL + src;
             }
             ParameterizedThreadStart pts = new ParameterizedThreadStart(DownloadImage);
             String folder = localFolder + "\\" + localFilename + manager.AddinSettings.MetaDataFolderSuffix;
             Object param = new ImageDownloadInfo(src, folder, imgInfo);
             pts.Invoke(param);
             src = folder + "\\" + Path.GetFileName(src);
             src = "file:///" + src.Replace("\\", "/");
             node.Attributes["src"].Value = src;
         }
     }
 }