示例#1
0
        /// <summary>
        /// Starting a delayed task.
        /// </summary>
        /// <param name="delayedAction">The delayed action.</param>
        /// <param name="waitTime">The timespan before invoking the action. (Milliseconds.)</param>
        /// <param name="repeat">The amount of times the action should be repeated.</param>
        public static uint StartDelayedTask(ThreadAction delayedAction, int waitTime, int repeat = 0)
        {
            DelayedAction taskAction = new DelayedAction();
            lock (SyncRoot)
            {
                taskAction.actionID = TaskID;
                TaskID++;
            }

            taskAction.allowedTime = DateTime.Now.AddMilliseconds(waitTime);
            taskAction.repeat = repeat;
            taskAction.threadAction = new ThreadAction(() =>
                                                       {
                                                       	if (DateTime.Now >= taskAction.allowedTime)
                                                       	{
                                                       		delayedAction.Invoke();
                                                       		if (taskAction.repeated >= taskAction.repeat)
                                                       		{
                                                       			DelayedAction outDA;
                                                       			taskObjects.TryRemove(taskAction.actionID, out outDA);
                                                       		}
                                                       		taskAction.repeated++;
                                                       	}
                                                       });
            taskObjects.TryAdd(taskAction.actionID, taskAction);
            return taskAction.actionID;
        }
示例#2
0
        /// <summary>
        /// Starting a delayed task.
        /// </summary>
        /// <param name="delayedAction">The delayed action.</param>
        /// <param name="waitTime">The timespan before invoking the action. (Milliseconds.)</param>
        /// <param name="repeat">The amount of times the action should be repeated.</param>
        public static uint StartDelayedTask(ThreadAction delayedAction, int waitTime, int repeat = 0)
        {
            DelayedAction taskAction = new DelayedAction();

            lock (SyncRoot)
            {
                taskAction.actionID = TaskID;
                TaskID++;
            }

            taskAction.allowedTime  = DateTime.Now.AddMilliseconds(waitTime);
            taskAction.repeat       = repeat;
            taskAction.threadAction = new ThreadAction(() =>
            {
                if (DateTime.Now >= taskAction.allowedTime)
                {
                    delayedAction.Invoke();
                    if (taskAction.repeated >= taskAction.repeat)
                    {
                        DelayedAction outDA;
                        taskObjects.TryRemove(taskAction.actionID, out outDA);
                    }
                    taskAction.repeated++;
                }
            });
            taskObjects.TryAdd(taskAction.actionID, taskAction);
            return(taskAction.actionID);
        }
    protected void Execute(Action action, string groupName = "", float delay = 0f, bool stopOnTimeScale = false)
    {
        //Debug.Log("Added item to thread with delay: " + delay);
        lock (Lock)
        {
            var neww = new ThreadAction
            {
                Action          = action,
                IsReady         = false,
                StopOnTimeScale = stopOnTimeScale,
                GroupName       = groupName
            };

            if (delay <= 0f)
            {
                neww.IsReady = true;
            }
            else
            {
                neww.Start(delay);
            }

            _actions.Add(neww);
        }
    }
示例#4
0
 /// <summary>
 /// Creating a new instance of ConquerOnline.MultiThreading.BaseThread.
 /// </summary>
 /// <param name="Action">The thread action.</param>
 /// <param name="Interval">The interval.</param>
 /// <param name="ThreadName">The thread name.</param>
 public BaseThread(ThreadAction Action, int Interval, string ThreadName)
 {
     this.Action         = Action;
     this.Interval       = Interval;
     running_thread      = new Thread(ThreadRun);
     running_thread.Name = ThreadName;
     check_thread        = new Thread(ThreadCheck);
 }
示例#5
0
 /// <summary>
 /// Creating a new instance of ConquerOnline.MultiThreading.BaseThread.
 /// </summary>
 /// <param name="Action">The thread action.</param>
 /// <param name="Interval">The interval.</param>
 /// <param name="ThreadName">The thread name.</param>
 public BaseThread(ThreadAction Action, int Interval, string ThreadName)
 {
     this.Action = Action;
     this.Interval = Interval;
     running_thread = new Thread(ThreadRun);
     running_thread.Name = ThreadName;
     check_thread = new Thread(ThreadCheck);
 }
示例#6
0
        public static bool CreateNewThread(ThreadAction action, IntPtr param)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            return(NativeMethods.create_new_thread(action.FunctionPointer, IntPtr.Zero));
        }
 public override void OnThreadFinished(ThreadAction threadAction)
 {
     if(isFinishing)
     {
         return;
     }
     ThreadAction action = new ThreadAction(threadAction.DoCallback);
     action.SignalFinishedCallback = threadAction.SignalFinishedCallback;
     action.Start();
 }
        public override void OnThreadFinished(ThreadAction threadAction)
        {
            if (isFinishing)
            {
                return;
            }
            ThreadAction action = new ThreadAction(threadAction.DoCallback);

            action.SignalFinishedCallback = threadAction.SignalFinishedCallback;
            action.Start();
        }
 public override void OnThreadFinished(ThreadAction threadAction)
 {
     lock (this.sync)
     {
         finishedThreadsCount++;
         if (finishedThreadsCount == threadActions.Count)
         {
             allThreadsAreFinishedSignal.Set();
         }
     }
 }
 public override void OnThreadFinished(ThreadAction threadAction)
 {
     if (isFinishing || ThreadAction.AllCanceled)
     {
         return;
     }
     ThreadAction action = new ThreadAction(threadAction.DoCallback);
     action.SignalFinishedCallback = threadAction.SignalFinishedCallback;
     this.threadActions.Add(action);
     action.Start();
 }
 public override void OnThreadFinished(ThreadAction threadAction)
 {
     lock (this.sync)
     {
         finishedThreadsCount++;
         if (finishedThreadsCount == threadActions.Count)
         {
             allThreadsAreFinishedSignal.Set();
         }
     }
 }
示例#12
0
        private void RunPoolThreads(int count, ThreadAction action)
        {
            // TODO: Run 'count' pool threads and execute 'action' in every one with appropriate range of data
            // TODO: Use 'ManualResetEvent' to synchronize operations
            var events = new List <ManualResetEvent>();

            for (int i = 0; i < count; i++)
            {
                var i1         = i;
                var resetEvent = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(_ => { action(i1 * _data.Length / count, (i1 + 1) * _data.Length / count); resetEvent.Set(); });
                events.Add(resetEvent);
            }
            WaitHandle.WaitAll(events.ToArray <WaitHandle>());
        }
示例#13
0
        /// <summary>
        /// deserialize a file to be used in the scenario
        /// </summary>
        /// <param name="filename"></param>
        public void Deserialize(string filename)
        {
            XmlSerializer xd = new XmlSerializer(typeof(Scenario));

            using (StreamReader rd = new StreamReader(filename))
            {
                Scenario scenario = xd.Deserialize(rd) as Scenario;

                Airports = sce­nario.Airports;
                foreach (Airport airport in Airports)
                {
                    airport.Reviver(this);
                }

                AirportNotifier();
                ThreadAction.Start();
            }
        }
        public ThreadAsync DoSomething(ThreadAction action, object obj = null)
        {
            ThreadAsync async  = null;
            Thread      thread = new Thread(() => {
                if (action != null)
                {
                    ThreadAction temp = action;
                    action            = null;
                    string error      = temp.Invoke(obj);
                    async.SetError(error);
                    async.SetIsDone(true);
                }
            });

            async = new ThreadAsync(thread);
            thread.Start();
            return(async);
        }
示例#15
0
        private void RunStandaloneThreads(int count, ThreadAction action)
        {
            // TODO: Run 'count' threads and execute 'action' in every one with appropriate range of data
            var t = new Thread[count];

            for (var i = 0; i < count; i++)
            {
                var i1 = i;
                t[i] = new Thread(() => action(i1 * _data.Length / count, (i1 + 1) * _data.Length / count));
            }

            foreach (var temp in t)
            {
                temp.Start();
            }
            foreach (var temp in t)
            {
                temp.Join();
            }
        }
示例#16
0
        internal override Action Clone(IDocumentEssential owner)
        {
            PDFDictionary dict = new PDFDictionary();

            dict.AddItem("Type", new PDFName("Action"));
            dict.AddItem("S", new PDFName("Thread"));

            IPDFObject fs = m_dictionary["F"];

            if (fs != null)
            {
                dict.AddItem("F", fs);
            }

            string[] keys = { "D", "B" };
            for (int i = 0; i < keys.Length; ++i)
            {
                IPDFObject obj = m_dictionary[keys[i]];
                if (obj != null)
                {
                    dict.AddItem(keys[i], obj.Clone());
                }
            }

            ThreadAction action = new ThreadAction(dict, owner);

            IPDFObject next = m_dictionary["Next"];

            if (next != null)
            {
                for (int i = 0; i < Next.Count; ++i)
                {
                    action.Next.Add(Next[i]);
                }
            }

            return(action);
        }
示例#17
0
 public ThreadWorker(ThreadAction action)
 {
     this.mAction = action;
     this.mWorkerLock = new object();
     this.mThread = new Thread(new ThreadStart(Work));
 }
示例#18
0
 private Task StartTask(ThreadAction action, CancellationToken cancellationToken)
 {
     var token = !cancellationToken.IsCancellationRequested ? cancellationToken : CancellationToken.None;
     return Task.Factory.StartNew(() => action(token), token, TaskCreationOptions.None, _callbackThread);
 }
示例#19
0
 public void InvokeOnUIThreadSync(ThreadAction action)
 {
     StartTask(action, _cancellationToken).Wait();
 }
        //=====================================================================

        /// <summary>
        /// This performs the requested task
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void actionThread_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadAction action = (ThreadAction)e.Argument;
            string       arguments, contentSetupFile;
            int          errorCode;

            runningThread = Thread.CurrentThread;

            try
            {
                HelpLibraryManager hlm = new HelpLibraryManager(viewerVersion);

                // Remove old content.  We'll remove it if installing to be sure that
                // the latest copy is installed.
                if (action == ThreadAction.Install || action == ThreadAction.Remove)
                {
                    if (action == ThreadAction.Install)
                    {
                        actionThread.ReportProgress(0, (int)ThreadState.RemovingOldContent);
                    }
                    else
                    {
                        actionThread.ReportProgress(0, (int)ThreadState.RemovingContent);
                    }

                    if (viewerVersion.Major == 1)
                    {
                        arguments = String.Format(CultureInfo.InvariantCulture,
                                                  "/product \"{0}\" /version \"{1}\" /locale {2} /uninstall /silent /vendor " +
                                                  "\"{3}\" /productName \"{4}\" /mediaBookList \"{5}\"",
                                                  project.CatalogProductId, project.CatalogVersion, project.Language.Name,
                                                  !String.IsNullOrEmpty(project.VendorName) ? project.VendorName : "Vendor Name",
                                                  !String.IsNullOrEmpty(project.ProductTitle) ? project.ProductTitle : project.HelpTitle,
                                                  project.HelpTitle);
                    }
                    else
                    {
                        arguments = String.Format(CultureInfo.InvariantCulture,
                                                  "/catalogName \"{0}\" /locale {1} /wait 0 /operation uninstall /vendor \"{2}\" " +
                                                  "/productName \"{3}\" /bookList \"{4}\" ",
                                                  project.CatalogName, project.Language.Name,
                                                  !String.IsNullOrEmpty(project.VendorName) ? project.VendorName : "Vendor Name",
                                                  !String.IsNullOrEmpty(project.ProductTitle) ? project.ProductTitle : project.HelpTitle,
                                                  project.HelpTitle);
                    }

                    // This doesn't have to run as an administrator
                    errorCode = hlm.RunAsNormalUser(arguments, ProcessWindowStyle.Minimized);

                    // Ignore it if not found and we are installing
                    if (errorCode != HelpLibraryManagerException.Success &&
                        (errorCode != HelpLibraryManagerException.NoBooksToInstall || action == ThreadAction.Remove))
                    {
                        throw new HelpLibraryManagerException(viewerVersion, errorCode);
                    }
                }

                if (action == ThreadAction.Install)
                {
                    // Install the new content
                    actionThread.ReportProgress(0, (int)ThreadState.InstallingContent);

                    // Copy the MSHA file to the required name
                    contentSetupFile = Path.Combine(Path.GetDirectoryName(setupFile), "HelpContentSetup.msha");
                    File.Copy(setupFile, contentSetupFile, true);

                    if (viewerVersion.Major == 1)
                    {
                        arguments = String.Format(CultureInfo.InvariantCulture, "/product \"{0}\" " +
                                                  "/version \"{1}\" /locale {2} /sourceMedia \"{3}\"", project.CatalogProductId,
                                                  project.CatalogVersion, project.Language.Name, contentSetupFile);
                    }
                    else
                    {
                        arguments = String.Format(CultureInfo.InvariantCulture, "/catalogName \"{0}\" " +
                                                  "/locale {1} /wait 0 /operation install /sourceUri \"{2}\"", project.CatalogName,
                                                  project.Language.Name, contentSetupFile);
                    }

                    // Always interactive and must run as administrator.  We can't run silently as we don't have
                    // a signed cabinet file.
                    errorCode = hlm.RunAsAdministrator(arguments, ProcessWindowStyle.Normal);

                    if (errorCode != HelpLibraryManagerException.Success)
                    {
                        throw new HelpLibraryManagerException(viewerVersion, errorCode);
                    }

                    // Open it if installed successfully
                    action = ThreadAction.OpenCurrent;
                }

                if (action == ThreadAction.OpenCurrent)
                {
                    arguments = null;

                    if (msHelpViewer == null)
                    {
                        msHelpViewer = hlm.HelpViewerPath;

                        if (msHelpViewer == null)
                        {
                            msHelpViewer = "ms-xhelp:///?method=page&id=-1";
                        }
                        else
                        if (viewerVersion.Major == 2)
                        {
                            arguments = "/catalogname \"" + project.CatalogName + "\"";
                        }
                    }

                    actionThread.ReportProgress(0, (int)ThreadState.OpeningContent);
                    System.Diagnostics.Process.Start(msHelpViewer, arguments);
                }
            }
            catch (ThreadAbortException)
            {
                // Ignore thread abort exceptions
            }
        }
 public abstract void OnThreadFinished(ThreadAction threadAction);
示例#22
0
 public abstract void OnThreadFinished(ThreadAction threadAction);
示例#23
0
        private Task StartTask(ThreadAction action, CancellationToken cancellationToken)
        {
            var token = !cancellationToken.IsCancellationRequested ? cancellationToken : CancellationToken.None;

            return(Task.Factory.StartNew(() => action(token), token, TaskCreationOptions.None, _callbackThread));
        }
示例#24
0
 internal void AttachThread(NsScriptThread thread)
 {
     thread.Process = this;
     PendingThreadActions.Enqueue(ThreadAction.Create(thread));
 }
示例#25
0
 public void InvokeOnUIThreadAsync(ThreadAction action)
 {
     StartTask(action, _cancellationToken);
 }
示例#26
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ExtremeKit.Threads"/> class.
		/// </summary>
		/// <param name="action">Action.</param>
		/// <param name="threadsCount">Threads count.</param>
		public Threads(ThreadAction action, int threadsCount) : this() {
			this.Action = action;
			this.Count  = threadsCount;
		}