Пример #1
0
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Now;

            TaskDelegate task        = Factorial;
            IAsyncResult asyncResult = task.BeginInvoke(2, 200000000, asycnCollback, task);
            long         s           = 0;
            //s=Factorial(2, 200000000);
            //while (!asyncResult.AsyncWaitHandle.WaitOne(1,false))
            //{
            //    Console.WriteLine(s);
            //}
            //long result = task.EndInvoke(asyncResult);
            ThreadStart threadStart = new ThreadStart(ssss);
            Thread      thread      = new Thread(threadStart);

            thread.Start();
            while (thread.ThreadState != ThreadState.Stopped)
            {
                Console.WriteLine("……");
            }
            Console.WriteLine(s);
            Console.WriteLine((DateTime.Now - dt));
            Console.Read();
        }
Пример #2
0
 /// <summary>
 /// 增加外部任务
 /// </summary>
 /// <param name="taskFunction">任务函数</param>
 /// <param name="delay">延迟执行事</param>
 /// <param name="taskName">任务名称</param>
 public void AddExternalTask(TaskDelegate taskFunction, double delay, string taskName)
 {
     lock (this)
     {
         externalTasks.Add(new ExternalTask(taskFunction, delay, taskName));
     }
 }
Пример #3
0
 /// <summary>
 /// 要延时执行的任务计算出它的实际执行时间,并把它添加到一个排好序的最小堆Task
 /// </summary>
 /// <param name="taskFunction">任务函数</param>
 /// <param name="delay">延迟执行事件</param>
 public void AddTask(TaskDelegate taskFunction, double delay, string taskName)
 {
     lock (this)
     {
         tasks.Add(new OriginalTask(taskFunction, DateTime.Now.AddSeconds(delay)));
     }
 }
Пример #4
0
 public void Choice()
 {
     while (true)
     {
         if (que.Count != 0)
         {
             TaskDelegate task = null;
             lock (obj)
             {
                 if (que.Count != 0)
                 {
                     task = que.Dequeue();
                 }
             }
             if (task != null)
             {
                 task();
                 Interlocked.Increment(ref myPath.count);
             }
         }
         else
         {
             break;
         }
     }
 }
Пример #5
0
        private void ThreadFuncton()
        {
            bool stopSignal = false;

            while (!stopSignal)
            {
                TaskDelegate currentTask = null;
                lock (taskDelegates)
                {
                    if (taskDelegates.Count > 0)
                    {
                        currentTask = taskDelegates.Dequeue();
                    }
                }
                if (currentTask != null)
                {
                    currentTask();
                }
                else
                {
                    lock (stopLockObject)
                    {
                        stopSignal = needToStop;
                    }
                }
            }
            ;
        }
Пример #6
0
        internal void LoadMessages()
        {
            TaskDelegate signal = delegate(object data)
            {
                if (data == null)
                {
                    Log.Write(new Exception("Failed to load messages."));
                    return;
                }

                var parameters = data as object[];
                LoadMessages(parameters[0] as List <BaseMessage>, (int)parameters[1]);
            };

            BaseMessage.RetrieveMessages(delegate(object data)
            {
                //Check if it is safe to interact with the form
                if (this.InvokeRequired)
                {
                    this.Invoke(signal, data);
                }
                else
                {
                    signal(data);
                }
            });
        }
Пример #7
0
 public void BeginInvoke()
 {
     taskDelegate = delegate()
     {
         try
         {
             Thread.CurrentThread.Name =
                 taskMethod.Name;
             testCase.AddCurrentThread();
             taskMethod.Invoke(testCase, null);
         }
         catch (Exception)
         {
             // Something went wrong, but we still have to keep the thread
             // alive until the ticker shuts down.
             try
             {
                 testCase.WaitForTick(int.MaxValue);
             }
             catch (Exception)
             {
                 // swallow this exception, because we're already
                 // dealing with ex.
             }
             throw;
         }
         // The thread finished successfully, now we just keep the thread
         // alive until the ticker shuts down.
         testCase.WaitForTick(int.MaxValue);
     };
     result = taskDelegate.BeginInvoke(null, null);
 }
        /// <summary>
        /// Retrieve polls from the server
        /// </summary>
        internal static void RetrievePolls(TaskDelegate onCompleteDelegate)
        {
            if (CurrentPolls != null)
            {
                onCompleteDelegate(CurrentPolls);
                return;
            }

            TaskHandler.RunTask(delegate(object data)
            {
                var parameters  = data as object[];
                var signal      = parameters[0] as TaskDelegate;
                var pollList = new List<ClientService.Poll>();

                try
                {
                    pollList.AddRange(ServiceHandler.Service.ListPolls(new ClientService.AuthenticatedData()));

                    CurrentPolls = pollList;
                }
                catch (Exception error)
                {
                    Log.Write(error);
                }

                //Signal to the calling thread that the operation is complete
                signal(pollList);

            }, onCompleteDelegate);
        }
Пример #9
0
 public void AddExternalTask(TaskDelegate taskFunction, double delay)
 {
     lock (this)
     {
         externalTasks.Add(new ExternalTask(taskFunction, delay, "Add task"));
     }
 }
Пример #10
0
 private void DoThreadWork()
 {
     while (true)
     {
         TaskDelegate task = DequeueTask();
         if (task != null)
         {
             try
             {
                 task();
             }
             catch (ThreadAbortException)
             {
                 Thread.ResetAbort();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }
         else
         {
             break;
         }
     }
 }
Пример #11
0
        private async Task SharingDesktopAsync()
        {
            if (!CheckIsUserSpeaking(true))
            {
                return;
            }

            AsynCallResult startResult = await _sdkService.StartScreenSharing();

            if (!HasErrorMsg(startResult.m_rc.ToString(), startResult.m_message))
            {
                _cancelSharingAction = async() =>
                {
                    AsynCallResult result = await _sdkService.StopScreenSharing();

                    if (!HasErrorMsg(result.m_rc.ToString(), result.m_message))
                    {
                        SharingVisibility       = Visibility.Visible;
                        CancelSharingVisibility = Visibility.Collapsed;
                    }
                };
                SharingVisibility       = Visibility.Collapsed;
                CancelSharingVisibility = Visibility.Visible;
            }
        }
Пример #12
0
        private async Task ExternalDataChangedAsync(string sourceName)
        {
            if (!CheckIsUserSpeaking(true))
            {
                return;
            }

            AsynCallResult openDataResult = await _sdkService.OpenSharedCamera(sourceName);

            if (!HasErrorMsg(openDataResult.m_rc.ToString(), openDataResult.m_message))
            {
                _cancelSharingAction = async() =>
                {
                    AsynCallResult result = await _sdkService.CloseSharedCamera();

                    if (!HasErrorMsg(result.m_rc.ToString(), result.m_message))
                    {
                        SharingVisibility       = Visibility.Visible;
                        CancelSharingVisibility = Visibility.Collapsed;
                    }
                };

                SharingVisibility       = Visibility.Collapsed;
                CancelSharingVisibility = Visibility.Visible;
            }
        }
Пример #13
0
        public void Test1()
        {
            DummyScheduler scheduler = new DummyScheduler();

            new Choker(2, scheduler.Call, new Flag());
            Assert.AreEqual(1, scheduler.FunctionCount);
            Assert.AreEqual(10.0, scheduler.GetDelay(0));
            TaskDelegate function = scheduler.GetFunction(0);

            function();

            scheduler.RemoveAt(0);
            Assert.AreEqual(1, scheduler.FunctionCount);
            Assert.AreEqual(10.0, scheduler.GetDelay(0));
            function = scheduler.GetFunction(0);
            function();

            scheduler.RemoveAt(0);
            function = scheduler.GetFunction(0);
            function();

            scheduler.RemoveAt(0);
            function = scheduler.GetFunction(0);
            function();

            scheduler.RemoveAt(0);
            scheduler.GetFunction(0);
        }
Пример #14
0
        void FormInstalador_Load(object sender, EventArgs e)
        {
            TaskDelegate td = new TaskDelegate(new ThreadStart(TheLongRunningTask));

            td.BeginInvoke(null, null); // Runs on a worker thread from the pool

            Dictionary <string, string> d = new Dictionary <string, string> ();

            if (!(Instalado.Installed(out d, "ORACLE DATABASE 11G EXPRESS")))
            {
                pbBd.Image = Resources.si;
            }


            if (Instalado.Installed(out d, "SISFALLA"))
            {
                button4.Text = "Desinstalar";
                if (d.ContainsKey("UninstallString"))
                {
                    string deinstall = d["UninstallString"];
                    deInstallSisfalla = deinstall.Replace("/I", "/x");
                }
            }
            else
            {
                button4.Visible = false;
            }
        }
Пример #15
0
    public bool GoToTalk(int key, TaskDelegate callback)
    {
        return(false);

        TaskConfig taskConfig = Globals.Instance.MDataTableManager.GetConfig <TaskConfig>();
        Dictionary <int, TaskConfig.TaskObject> taskObjectDic;

        taskConfig.GeTaskObjectList(out taskObjectDic);

        int       taskid = -1;
        TALKSTATE state  = TALKSTATE.BEFORE;

        for (int i = 0; i < Globals.Instance.MTaskManager._mUnfinishList.Count; i++)
        {
            TaskData taskData = Globals.Instance.MTaskManager._mUnfinishList[i];
            if (taskData.IsTaskDaily)
            {
                continue;                //xiu gai ren wu wu fa ti jiao; 20121009
                //break;
            }

            //if( Globals.Instance.MGameDataManager.MCurrentPortData.PortID == taskObjectDic[taskData.Task_ID].Complete_Task_SeaID)
            {
                if (taskData != null && taskData.State == TALKSTATE.COMPLETE)
                {
                    taskid = taskData.Task_ID;
                }
            }
        }

        for (int i = 0; i < Globals.Instance.MTaskManager._mCanAcceptList.Count; i++)
        {
            if (!taskObjectDic.ContainsKey(Globals.Instance.MTaskManager._mCanAcceptList[i]))
            {
                continue;
            }
            //if( Globals.Instance.MGameDataManager.MCurrentPortData.PortID == taskObjectDic[Globals.Instance.MTaskManager._mCanAcceptList[i]].Before_Task_SeaID)
            {
                taskid = Globals.Instance.MTaskManager._mCanAcceptList[i];
            }
        }

        if (taskid == -1)
        {
            return(false);
        }

        Globals.Instance.MTaskManager.mCurTaskId = taskid;

        GUIRadarScan.Show();
        Globals.Instance.MGUIManager.CreateWindow <GUITaskTalkView>(
            delegate(GUITaskTalkView gui)
        {
            GUIRadarScan.Hide();
            gui.UpdateData(taskid, delegate(){ callback(); });
        }
            );

        return(true);
    }
        private void ThreadFuncton()
        {
            bool stopSignal = false;

            while (!stopSignal)
            {
                TaskDelegate currentTask = null;
                lock (taskDelegates)
                {
                    if (taskDelegates.Count > 0)
                    {
                        currentTask = taskDelegates.Dequeue();
                    }
                }
                if (currentTask != null)
                {
                    //Console.WriteLine(Thread.CurrentThread.Name + " started task.");
                    currentTask();
                    //Console.WriteLine(Thread.CurrentThread.Name + " finished task.");
                }
                else
                {
                    lock (stopLockObject)
                    {
                        stopSignal = needToStop;
                    }
                }
            }
            ;
        }
Пример #17
0
 public void EnqueueTask(TaskDelegate task)
 {
     lock (_syncRoot)
     {
         _tasksQueue.Enqueue(task);
     }
 }
Пример #18
0
        /// <summary>
        /// Retrieve polls from the server
        /// </summary>
        internal static void RetrievePolls(TaskDelegate onCompleteDelegate)
        {
            if (CurrentPolls != null)
            {
                onCompleteDelegate(CurrentPolls);
                return;
            }

            TaskHandler.RunTask(delegate(object data)
            {
                var parameters = data as object[];
                var signal     = parameters[0] as TaskDelegate;
                var pollList   = new List <ClientService.Poll>();

                try
                {
                    pollList.AddRange(ServiceHandler.Service.ListPolls(new ClientService.AuthenticatedData()));

                    CurrentPolls = pollList;
                }
                catch (Exception error)
                {
                    Log.Write(error);
                }

                //Signal to the calling thread that the operation is complete
                signal(pollList);
            }, onCompleteDelegate);
        }
Пример #19
0
 public void EnqueueTask(TaskDelegate task)
 {
     mutex.WaitOne();
     _taskQueue.Enqueue(task);
     mutex.ReleaseMutex();
     fillCnt.Release(1);
 }
Пример #20
0
        // method to be invoked when a thread begins executing
        private void PerformTask()
        {
            while (true)
            {
                while (_tasks.IsEmpty)
                {
                }

                // get another task
                TaskDelegate task = _tasks.Dequeue();

                if (task == null)
                {
                    continue;
                }

                Interlocked.Increment(ref _activeThreads);
                try
                {
                    // execute the task
                    task();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
                Interlocked.Decrement(ref _activeThreads);
            }
        }
Пример #21
0
        public void ThreadProc()
        {
            TaskDelegate del  = null;
            string       file = "";
            string       dest = "";

            while (true)
            {
                lock (this)
                {
                    if (TaskDelegates.Count > 0)
                    {
                        del  = TaskDelegates[0];
                        file = filePaths[0];
                        dest = destPaths[0];

                        TaskDelegates.RemoveAt(0);
                        filePaths.RemoveAt(0);
                        destPaths.RemoveAt(0);
                    }
                }

                if (del != null)
                {
                    del(file, dest);
                    file = "";
                    dest = "";
                    del  = null;
                }
            }
        }
Пример #22
0
        private void TaskSelectionQueue()
        {
            while (_isActive)
            {
                TaskDelegate taskDelegate = null;
                bool         taskReady    = false;

                lock (_queueSync)
                {
                    if (_taskQueue.Count == 0)
                    {
                        Monitor.Wait(_queueSync);
                    }
                    else
                    {
                        taskReady    = true;
                        taskDelegate = _taskQueue.Dequeue();
                        Monitor.Pulse(_queueSync);
                    }
                }
                if (taskReady)
                {
                    taskDelegate();
                }
            }
        }
 public TaskData(string title, bool blockUI, System.Func <bool> precondition, TaskDelegate taskFunction) : base(title)
 {
     m_blockUI      = blockUI;
     m_precondition = precondition;
     m_taskFunction = taskFunction;
     m_context      = new TaskContext(this);
 }
Пример #24
0
 private void ThreadLoop()
 {
     while (_isWorking)
     {
         TaskDelegate task = null;
         lock (_locker)
         {
             if (_taskQueue.Count == 0)
             {
                 _lockedCounter++;
                 Monitor.Wait(_locker);
                 _lockedCounter--;
             }
             else
             {
                 task = _taskQueue.Dequeue();
                 _counter++;
                 Monitor.Pulse(_locker);
             }
         }
         if (task != null)
         {
             task();
             Interlocked.Decrement(ref _counter);
         }
     }
 }
Пример #25
0
        public void ThreadProc()
        {
            TaskDelegate del = null;

            Thread.Sleep(50);

            while (true)
            {
                lock (this)
                {
                    if (TaskDelegates.Count > 0)
                    {
                        del = TaskDelegates[0];
                        TaskDelegates.RemoveAt(0);
                    }
                }

                if (del != null)
                {
                    threads[Thread.CurrentThread] = true;
                    del();
                    del = null;
                    threads[Thread.CurrentThread] = false;
                }
            }
        }
Пример #26
0
 public void EnqueueTask(TaskDelegate task)
 {
     lock (taskDelegates)
     {
         taskDelegates.Enqueue(task);
     }
 }
Пример #27
0
 public void trigger(TaskDelegate task)
 {
     if (remaining > 0)
     {
         remaining -= 1;
         task();
     }
 }
Пример #28
0
 public void EnqueueTask(TaskDelegate task)
 {
     lock (tasks)
     {
         tasks.Enqueue(task);
         Monitor.Pulse(tasks);
     }
 }
Пример #29
0
 /**
  * Add task to queue.
  */
 public virtual void EnqueueTask(TaskDelegate taskDelegate)
 {
     lock (_monitorVariable)
     {
         _tasksQueue.Enqueue(taskDelegate);
         Monitor.Pulse(_monitorVariable); // Notify slept tread that there is new task
     }
 }
Пример #30
0
 public void EnqueueTask(TaskDelegate task)
 {
     lock (_queueSync)
     {
         _taskQueue.Enqueue(task);
         Monitor.Pulse(_queueSync);
     }
 }
Пример #31
0
 public void EnqueueTask(TaskDelegate task)
 {
     if (disposed)
     {
         throw new ObjectDisposedException(null);
     }
     _taskPull.Enqueue(task);
 }
        /// <summary>
        /// Retrieve messages from server if messages are not stored locally
        /// </summary>
        public static void RetrieveMessages(TaskDelegate onCompleteDelegate)
        {
            //Check the message datastore to see if messages have already been loaded
            var messages = Messages;

            if (messages == null)
                messages = new List<BaseMessage>();

            //If not, retrieve the message list from the server
            TaskHandler.RunTask(delegate(object data)
            {
                var parameters  = data as object[];
                var signal      = parameters[0] as TaskDelegate;
                var dataStore   = parameters[1] as DataStore;
                var list        = parameters[2] as List<BaseMessage>;
                var newItems    = 0;

                try
                {
                    ListMessageResult listMessageResult     = ServiceHandler.Service.ListMessages(new AuthenticatedData());
                    var insertionList = new List<BaseMessage>();
                    newItems = listMessageResult.Messages.Length;

                    foreach (var message in listMessageResult.Messages)
                    {
                        insertionList.Add(new BaseMessage()
                        {
                            Id          = message.Id,
                            Subject     = message.Subject,
                            Message     = message.Message,
                            Sender      = message.Sender,
                            DateToSend  = message.DateToSend,
                            DateExpires = message.DateExpires,
                            DateCreated = message.DateCreated
                        });
                    }

                    list.InsertRange(0, insertionList);

                    //Store callsign list to datastore
                    dataStore[MessageKey] = list;
                    dataStore.Save();
                }
                catch (Exception error)
                {
                    Log.Write(error);
                }

                //Signal to the calling thread that the operation is complete
                signal(new object[] { list, newItems });

            }, onCompleteDelegate, MessageStore, messages);
        }
Пример #33
0
 public bool StartAsyncTask(TaskDelegate Task)
 {
     if (null != Task && this.taskCompletedEvent.WaitOne(0, false))
     {
         this.taskCompletedEvent.Reset();
         this.exception = null;
         if (ThreadPool.QueueUserWorkItem(this.PerformTask, Task))
             return true;
         else
             this.taskCompletedEvent.Set();
     }
     return false;
 }
        public static Thread CheckAvailability(string desiredCallsign, string asgsPassword, bool canCreate, TaskDelegate onCompleteDelegate)
        {
            if(string.IsNullOrEmpty(desiredCallsign))
            {
                onCompleteDelegate(CheckAliasResult.Unavailable);
                return null;
            }

            return TaskHandler.RunTask(delegate(object data)
            {
                var parameters  = data as object[];
                var signal      = parameters[0] as TaskDelegate;
                var callsign    = parameters[1] as string;
                var create      = (bool)parameters[2];

                bool specified;
                CheckAliasResult result;

                try
                {
                    result = ValidateLegacyCallsignUsage(desiredCallsign, asgsPassword);
                    if (result != CheckAliasResult.Available)
                    {
                        specified = true;
                    }
                    else
                    {
                        if (create)
                            ServiceHandler.Service.CreateAlias(new LoginData() { Alias = callsign, LegacyPassword = asgsPassword }, out result, out specified);
                        else
                            ServiceHandler.Service.CheckAlias(new LoginData() { Alias = callsign, LegacyPassword = asgsPassword }, out result, out specified);
                    }
                }
                catch (Exception error)
                {
                    specified   = false;
                    result      = CheckAliasResult.Unavailable;

                    Log.Write(error);
                }

                //Signal the calling threat that the operation is compete
                if (specified)
                    onCompleteDelegate(result);
                else
                    onCompleteDelegate(CheckAliasResult.Unavailable);

            }, onCompleteDelegate, desiredCallsign, canCreate);
        }
        public static void SetStatusBar(string text, int percentage)
        {
            var signal = new TaskDelegate(delegate(object parameter)
            {
                FormInstance._loginStatusStrip.Items[0].Text = parameter as string;

                var pb = FormInstance._loginStatusStrip.Items[1] as ToolStripProgressBar;
                pb.Value = percentage;

                FormInstance.StatusTimer.Stop();
                FormInstance.StatusTimer.Start();
            });

            if (FormInstance.InvokeRequired)
                FormInstance.Invoke(signal, text);
            else
                signal(text);
        }
        // This is different from the alias check as it's used in account creation before the user
        // as AuthenticatedData to talk to the web service with.
        public static Thread CheckUsernameAvailability(string username, TaskDelegate onCompleteDelegate)
        {
            if (string.IsNullOrEmpty(username))
            {
                onCompleteDelegate(CheckAliasResult.Unavailable);
                return null;
            }

            return TaskHandler.RunTask(delegate(object data)
            {
                var parameters = data as object[];
                var signal = parameters[0] as TaskDelegate;
                var targetUsername = parameters[1] as string;

                bool specified;
                CheckAliasResult result;

                try
                {
                    ServiceHandler.Service.IsAliasAvailable(targetUsername, out result, out specified);
                }
                catch (Exception error)
                {
                    specified = false;
                    result = CheckAliasResult.Unavailable;

                    Log.Write(error);
                }

                //Signal the calling threat that the operation is compete
                if (specified)
                    onCompleteDelegate(result);
                else
                    onCompleteDelegate(CheckAliasResult.Unavailable);

            }, onCompleteDelegate, username);
        }
Пример #37
0
		public void AddQueue(TaskDelegate TaskDelegate)
		{
			Tasks.Enqueue(TaskDelegate);
			Timer.Start();
		}
        /// <summary>
        /// Perform autoupdate, validate client, negotiate for new session
        /// </summary>
        public static void Login(string aliasInput, string lobbyName, TaskDelegate onCompleteDelegate)
        {
            TaskHandler.RunTask(delegate(object input) {

                DebugDetector.AssertCheckRunning();

                var parameters  = input as object[];
                var signal      = parameters[0] as TaskDelegate;
                var alias       = parameters[1] as string;
                var message     = string.Empty;
                var ticket      = string.Empty;
                var rank		= 0;
                CheckInStatus status = CheckInStatus.InvalidCredentials;

                try
                {
                    //Get available lobbies
                    MainForm.SetStatusBar("Checking lobby status...", 25);
                    var lobbies = ServiceHandler.Service.CheckAvailableLobbies();

                    //Get lobby
                    var lobby   = GetLobbyByName(lobbies, lobbyName);

                    //Check auto-update - This is done by the play control/update check control now.
                    //MainForm.SetStatusBar("Checking for updates...", 25);

                    //PendingUpdates pendingUpdates = AutoUpdate.GetPendingUpdateQueues(ServiceHandler.Service);

                    //if (AutoUpdate.ProcessPendingUpdates(pendingUpdates, lobby, new AutoUpdate.AutoupdateProgressCallback(AutoupdateProgressUpdate)))
                    //    return;

                    //Log in, Display 'logging in' status to user
                    MainForm.SetStatusBar("Logging in...", 50);

                    var loginResult = ServiceHandler.Service.Login(new LoginData()
                    {
                        Alias               = alias,
                        LobbyId             = lobby.LobbyId,
                        LobbyIdSpecified    = true
                    });

                    if (loginResult.StatusSpecified)
                    {
                        rank = loginResult.Rank;

                        switch (loginResult.Status)
                        {
                            case LoginStatus.Authenticated:

                                //Perform initial check in
                                MainForm.SetStatusBar("Validating Client...", 75);
                                status = ValidateLogin(loginResult.BlackboxData, ref message, ref ticket);

                                // Relog in after linking to pick up any alias changes.
                                if (status == CheckInStatus.AccountLinked)
                                {
                                    loginResult = ServiceHandler.Service.Login(new LoginData()
                                    {
                                        Alias = alias,
                                        LobbyId = lobby.LobbyId,
                                        LobbyIdSpecified = true
                                    });
                                }

                                //Set up response
                                alias = loginResult.AcceptedAlias;

                                //if (loginResult.Rank <= 5)
                                //    alias += "(" + loginResult.Rank.ToString() + ")";

                                break;

                            case LoginStatus.AccountLocked:
                                message = "Account Locked";
                                break;

                            case LoginStatus.InvalidCredentials:
                                message = "Username or password was incorrect";
                                break;

                            case LoginStatus.PermissionDenied:
                                message = "Permission was denied to this lobby";
                                break;

                        }
                    }
                    else
                    {
                        message = "An unknown error occurred";
                    }

                    Log.Write(message);
                }
                catch (Exception error)
                {
                    message = "An error occurred";

                    Log.Write(error);
                }

                //Signal the calling thread
                signal(new object[] { status, message, alias, ticket, rank });

            }, onCompleteDelegate, aliasInput);
        }
        internal void LoginToLobby(LobbyType lobbyType)
        {
            //Verify the form is filled out
            if (string.IsNullOrEmpty(_loginComboBox.Text))
                return;

            // TODO: Figure out where the alleg exe is and send it to the launcher.

            //Create a new session
            var signal = new TaskDelegate(delegate(object input)
            {
                var parameters  = input as object[];
                var status   = (CheckInStatus)parameters[0];
                var message     = parameters[1] as string;
                var alias       = parameters[2] as string;
                var ticket      = parameters[3] as string;

                int rank = 0;

                if (parameters[4] != null)
                    rank = (int)parameters[4];

                Regex aliasFinder = new Regex(
                      "(?<callsign>.*?)(\\(\\d+\\))?$",
                    RegexOptions.ExplicitCapture
                    | RegexOptions.CultureInvariant
                    | RegexOptions.Compiled
                    );

                var match = aliasFinder.Match(alias);
                if (match.Success == true)
                    alias = match.Groups["callsign"].Value;

                if (status == CheckInStatus.AccountLinked)
                {
                    if (ReloadCallsigns != null)
                        ReloadCallsigns();
                }

                if (status == CheckInStatus.Ok || status == CheckInStatus.AccountLinked)
                {
                    //Initialize check-in interval
                    CheckInTimer            = new Timer();
                    CheckInTimer.Interval   = CheckInInterval;
                    CheckInTimer.Tick       += new EventHandler(CheckInTimer_Tick);
                    CheckInTimer.Start();

                    //Launch Allegiance
                    MainForm.SetStatusBar("Launching Allegiance...");

                    //Store last-used alias
                    if (!string.Equals(DataStore.LastAlias, alias))
                    {
                        DataStore.LastAlias = alias;
                        DataStore.Instance.Save();
                    }

                    if (rank <= 5)
                        alias += "(" + rank + ")";

                    AllegianceLoader.StartAllegiance(ticket, lobbyType, alias, delegate(object param)
                    {
                        var result = (bool)param;

                        if (!result)
                        {
                            Logout();

                            MainForm.SetStatusBar("Failed to launch Allegiance.");
                        }
                        else
                        {
                            //AllegianceLoader.AllegianceProcess.OnExiting
                              //  += new EventHandler(AllegianceProcess_OnExiting);

                            AllegianceLoader.AllegianceExit
                                += new EventHandler(AllegianceProcess_OnExiting);
                        }
                    });

                    SetLoggedIn(true);

                    if (DataStore.Preferences.AutoLogin)
                        MainForm.HideForm();
                }
                else
                {
                    MainForm.SetStatusBar(message);

                    if (status == CheckInStatus.VirtualMachineBlocked)
                    {
                        VirtualMachineInfo virtualMachineInfo = new VirtualMachineInfo();
                        virtualMachineInfo.ShowDialog();
                    }

                    this.Enabled = true;

                    SystemWatcher.Close();
                }
            });

            SessionNegotiator.Login(_loginComboBox.Text, lobbyType.ToString(), delegate(object input)
            {
                if (this.InvokeRequired)
                    this.Invoke(signal, input);
                else
                    signal(input);
            });
        }
Пример #40
0
 /// <summary>
 /// .net2.0中线程安全访问控件扩展方法,可以获取返回值,可能还有其它问题
 /// </summary>
 /// CrossThreadCalls.SafeInvoke(this.statusStrip1, new CrossThreadCalls.TaskDelegate(delegate()
 /// {
 ///    tssStatus.Text = "开始任务...";
 /// }));
 /// CrossThreadCalls.SafeInvoke(this.rtxtChat, new CrossThreadCalls.TaskDelegate(delegate()
 /// {
 ///     rtxtChat.AppendText("测试中");
 /// }));
 /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
 /// <summary>
 public static void SafeInvoke(Control control, TaskDelegate handler)
 {
     if (control.InvokeRequired)
     {
         while (!control.IsHandleCreated)
         {
             if (control.Disposing || control.IsDisposed)
                 return;
         }
         IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
         control.EndInvoke(result);//获取委托执行结果的返回值
         return;
     }
     IAsyncResult result2 = control.BeginInvoke(handler);
     control.EndInvoke(result2);
 }
Пример #41
0
 /// <summary>
 /// ���������������
 /// ���������TaskDelegateί�нӿڵ�worker��������
 /// </summary>
 /// <param name="worker">��������</param>
 /// <param name="args">����IJ�������</param>
 public bool StartTask(TaskDelegate worker ,params object[] args )
 {
     bool result =false;
     lock( this )
     {
         if( IsStop && worker != null )
         {
             _result = null;
             _callThread = System.Threading.Thread.CurrentThread;
             // ��ʼ������������,�첽����,���ͻص�����
             worker.BeginInvoke( args ,new AsyncCallback( EndWorkBack ), worker );
             // ����������״̬
             _taskState = TaskStatus.Running;
             // ����������״̬�仯�¼�
             FireStatusChangedEvent( _taskState, null);
             result = true;
         }
     }
     return result;
 }
        private void UpdateCheck_Load(object sender, EventArgs e)
        {
            _updateStatusLabel.Text = String.Empty;

            TaskHandler.RunTask(delegate(object input)
            {
                object[] parameters = input as object[];
                UpdateCheckControl formReference = parameters[0] as UpdateCheckControl;

                DebugDetector.AssertCheckRunning();

                if (HasPendingUpdates == true)
                {

                    var signal = new TaskDelegate(delegate(object data)
                        {
                            var updateCount = Convert.ToInt32(data);

                            if (MessageBox.Show(new Form() { TopMost = true }, "Free Allegiance Updater has " + updateCount + " files to download.\nYou will not be able to play until these updates are installed.\nWould you like to do this now?", "New updates found!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                            {
                                MessageBox.Show(new Form() { TopMost = true }, "Please restart the application when you are ready to apply updates.", "Update Canceled", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                Application.Exit();
                            }
                        });

                    if (this.InvokeRequired == true)
                        this.Invoke(signal, PendingUpdates.PendingUpdateCount);
                    else
                        signal(PendingUpdates.PendingUpdateCount);

                }
                else
                {
                    return;
                }

                //Get available lobbies
                UpdateProgress(String.Empty, "Checking lobby status...", 0);
                var lobbies = ServiceHandler.Service.CheckAvailableLobbies();

                foreach (var lobby in lobbies)
                {
                    if (formReference._abortUpdate == true)
                        break;

                    UpdateProgress(lobby.Name, "Checking lobby for updates.", 0);

                    if (AutoUpdate.ProcessPendingUpdates(PendingUpdates, lobby, new AutoUpdate.AutoupdateProgressCallback(UpdateProgress), this))
                        return;
                }

                TaskDelegate onUpdateCompleteHandler = delegate(object data)
                {
                    UpdateCheckControl updateCompleteFormReference = data as UpdateCheckControl;

                    if (AutoupdateComplete != null)
                        AutoupdateComplete(updateCompleteFormReference._abortUpdate);
                };

                if(formReference.InvokeRequired == true)
                    formReference.Invoke(onUpdateCompleteHandler, formReference);
                else
                    onUpdateCompleteHandler(formReference);

            }, this);
        }
        public static void SetStatusBar(string text, int percentage)
        {
            if (FormInstance == null)
                return;

            var signal = new TaskDelegate(delegate(object parameter)
            {
                var msg = parameter as string;

                // BT - This was throwing an exception during launcher shutdown.
                // It's still a race, but maybe this is good enough.
                if (FormInstance._mainStatusStrip.Items.Count > 0)
                {
                    FormInstance._mainStatusStrip.Items[0].Text = msg;

                    var pb = FormInstance._mainStatusStrip.Items[1] as ToolStripProgressBar;
                    pb.Value = percentage;
                    pb.Visible = percentage > 0;
                }

                FormInstance.StatusTimer.Stop();
                FormInstance.StatusTimer.Start();

                if(!FormInstance.Visible)
                    FormInstance.DisplayNotificationMessage(msg);
            });

            if (FormInstance.InvokeRequired)
                FormInstance.Invoke(signal, text);
            else
                signal(text);
        }
        private void CheckPolls()
        {
            var signal = new TaskDelegate(delegate(object data)
            {
                var list = data as List<ClientService.Poll>;
                if (list.Count > 0)
                {
                    PresentPoll(list);
                    SetStatusBar("Poll(s) Received");
                }
            });

            Allegiance.CommunitySecuritySystem.Client.Service.Poll.RetrievePolls(delegate(object data)
            {
                if (InvokeRequired)
                    Invoke(signal, data);
                else
                    signal(data);
            });
        }
        void _playControl_AllegianceExited()
        {
            SetStatusBar("Allegiance Exited.");

            var signal = new TaskDelegate(delegate(object parameter)
            {
                if (this.Visible == false)
                    Close();
            });

            if (FormInstance.InvokeRequired)
                FormInstance.Invoke(signal, this);
            else
                signal(this);
        }
        void _playControl_ReloadCallsigns()
        {
            var signal = new TaskDelegate(delegate(object data)
                {
                    _callsignControl.LoadCallsigns(true);
                });

            if(_callsignControl.InvokeRequired == true)
                _callsignControl.Invoke(signal);
            else
                signal(null);
        }
        void _timer_Tick(object sender, EventArgs e)
        {
            string usernameAvailableMessage = "Callsign is available";
            string usernameUnavailableMessage = "Callsign is unavailable";
            string usernameAlreadyRegisteredMessage = "Callsign is Already Registered";
            List<string> responseMessages = new List<string>(new string[] { usernameAvailableMessage, usernameUnavailableMessage, usernameAlreadyRegisteredMessage });

            _timer.Stop();

            if (_activeThread != null)
                _activeThread.Abort();

            if (_callsignTextBox.Text.Length == 0)
            {
                _activeThread = null;
                return;
            }

            string errorMessage;
            if (Validation.ValidateAlias(_callsignTextBox.Text, out errorMessage) == false)
            {
                _setCheckMessage(errorMessage);
                _errorProvider.SetError(_callsignTextBox, errorMessage);
            }
            else
            {
                _errorProvider.SetError(_callsignTextBox, "");
            }

            string currentValidationMessage = _errorProvider.GetError(_callsignTextBox);

            // If there is any validation message other than an account status message.
            if (responseMessages.Contains(currentValidationMessage) == false && string.IsNullOrEmpty(currentValidationMessage) == false)
                return;

            _setCheckMessage("Checking Availability...");

            //Check if requested callsign is available (every n milliseconds at most)
            var signal = new TaskDelegate(delegate(object input)
            {

                var result = (CheckAliasResult)input;
                var message = string.Empty;

                switch (result)
                {
                    case CheckAliasResult.Available:
                        message = usernameAvailableMessage;
                        _continueButton.Enabled = true;
                        _legacyPasswordPanel.Visible = false;
                        _errorProvider.SetError(_callsignTextBox, "");
                        break;

                    case CheckAliasResult.Unavailable:
                        message = usernameUnavailableMessage;
                        _errorProvider.SetError(_callsignTextBox, usernameUnavailableMessage);
                        break;

                    case CheckAliasResult.Registered:
                        message = usernameAlreadyRegisteredMessage;
                        _errorProvider.SetError(_callsignTextBox, usernameAlreadyRegisteredMessage);
                        break;

                    case CheckAliasResult.InvalidLogin:
                        message = "Invalid Credentials";
                        break;

                    case CheckAliasResult.AliasLimit:
                        message = "You already have the maximum number of callsigns.";
                        break;

                    case CheckAliasResult.LegacyExists:
                        message = "Please use ASGS password to create callsign!";
                        _continueButton.Enabled = true;
                        _legacyPasswordPanel.Visible = true;
                        _errorProvider.SetError(_callsignTextBox, "");
                        break;
                }

                _setCheckMessage(message);
            });

            _activeThread = Callsign.CheckUsernameAvailability(_callsignTextBox.Text, delegate(object data)
            {
                if (System.Threading.Thread.CurrentThread != _activeThread)
                    return;

                if (_callsignTextBox.InvokeRequired)
                    _callsignTextBox.Invoke(signal, data);
                else
                    signal(data);
            });
        }
        public static void StartAllegiance(string ticket, LobbyType lobbyType, string alias, TaskDelegate onCompleteDelegate)
        {
            DebugDetector.AssertCheckRunning();

            TaskHandler.RunTask(delegate(object p)
            {
                var param = p as object[];
                var sessionTicket = param[0] as string;
                var signal = param[1] as TaskDelegate;
                var succeeded = false;

                try
                {
					AllegianceRegistry.OutputDebugString = DataStore.Preferences.DebugLog;
					AllegianceRegistry.LogToFile = DataStore.Preferences.DebugLog;
                    AllegianceRegistry.LogChat = DataStore.Preferences.LogChat;

                    //Create commandline
                    var commandLine = new StringBuilder("-authenticated")
						.AppendFormat(" -callsign={0}", alias);

					if (DataStore.Preferences.DebugLog)
						commandLine.Append(" -debug");
						
                    if (DataStore.Preferences.LaunchWindowed)
                        commandLine.Append(" -windowed");

                    if (DataStore.Preferences.NoMovies)
                        commandLine.Append(" -nomovies");

                    //Start Allegiance
                    string lobbyPath = Path.Combine(AllegianceRegistry.LobbyPath, lobbyType.ToString());

					string allegiancePath = Path.Combine(lobbyPath, "Allegiance.exe");

					if(DataStore.Preferences.UseDX7Engine == true)
						allegiancePath = Path.Combine(lobbyPath, "AllegianceDX7.exe");
					

#if DEBUG
						if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["AllegianceExeOverride"]) == false)
						{
							Log.Write("Allegiance path was overridden by configuration setting.");
							allegiancePath = ConfigurationManager.AppSettings["AllegianceExeOverride"];
						}
#endif

                    Log.Write("Using: " + allegiancePath + " " + commandLine.ToString() + " to launch...");

                    ProcessHandler process = ProcessHandler.Start(allegiancePath, commandLine.ToString());

					process.OnExiting += new EventHandler(process_OnExiting);

					_allegianceProcess = process;
					_allegianceProcessMonitor = new ProcessMonitor(_allegianceProcess);

					// If launching into a lobby, then relay the security token to the allegiance process.
					if (lobbyType != LobbyType.None)
					{
						//Open Pipe
						using (var reset = new ManualResetEvent(false))
						{
							TaskHandler.RunTask(delegate(object value)
							{
								var parameters = value as object[];
								var localProcessHandler = parameters[0] as ProcessHandler;
								var localSessionTicket = parameters[1] as String;
								var localReset = parameters[2] as ManualResetEvent;

								using (var pipe = new Pipe(@"\\.\pipe\allegqueue"))
								{
									pipe.Create();

									if (pipe.Connect())
									{
										Int64 memoryLocation = Int64.Parse(pipe.Read());

										localProcessHandler.WriteMemory(memoryLocation, localSessionTicket + (char) 0x00 + Process.GetCurrentProcess().Id);

										localReset.Set();
									}
								}

							}, process, sessionTicket, reset);


							//Wait X seconds, if allegiance does not retrieve the ticket, exit Allegiance.
							if (!reset.WaitOne(PipeTimeout))
							{
								try
								{
									process.ForceClose();

									//Connect to the pipe in order to close out the connector thread.
									using (var pipe = new Pipe(@"\\.\pipe\allegqueue"))
									{
										pipe.OpenExisting();
										pipe.Read();
									}
								}
								catch { }
								finally
								{
									throw new Exception("Allegiance did not respond within the time allotted.");
								}
							}

							// The memory address was retrived from the pipe, write the ticket onto the target process.
							//process.WriteMemory((Int64) memoryLocation, sessionTicket);      
						}
					}

                    succeeded = true;
                }
                catch (Exception error)
                {
                    Log.Write(error);
                }
                finally
                {
                    signal(succeeded);
                }
            }, ticket, onCompleteDelegate);
        }
        private void _createButton_Click(object sender, EventArgs e)
        {
            if (_legacyPasswordPanel.Visible == true &&  String.IsNullOrEmpty(_asgsPasswordTextbox.Text) == true)
            {
                _errorProvider.SetError(_asgsPasswordTextbox, "Please specify your ASGS password to claim this callsign.");
                return;
            }

            //Lock the form
            SetEnabled(false);

            var signal = new TaskDelegate(delegate(object input)
            {
                var callsignCreationResult = (CheckAliasResult)input;

                switch (callsignCreationResult)
                {
                    case CheckAliasResult.Registered:
                        if (CallsignCreated != null)
                            CallsignCreated(this, _newCallsignTextBox.Text);

                        break;

                    case CheckAliasResult.CaptchaFailed:
                        SetCheckMessage("Invalid captcha code specified, callsign not created.");
                        break;

                    case CheckAliasResult.InvalidLogin:
                        SetCheckMessage("Invalid login, callsign not created.");
                        break;

                    case CheckAliasResult.Unavailable:
                        SetCheckMessage("This callsign is no longer available.");
                        break;

                    case CheckAliasResult.AliasLimit:
                        SetCheckMessage("You already have the maximum number of aliases.");
                        break;

                    case CheckAliasResult.InvalidLegacyPassword:
                        SetCheckMessage("Invalid ASGS password specified.");
                        MessageBox.Show("You are tring to register a callsign that was used in the previous security system. You will need to use your original password to unlock your old callsign. If you do not have this password, please contact the administrators through the forums.");
                        break;

                    default:
                        SetCheckMessage("Callsign not created: " + callsignCreationResult.ToString());
                        break;
                }

                SetEnabled(true);
            });

            //Ask server to create this callsign
            Callsign.CheckAvailability(_newCallsignTextBox.Text, _asgsPasswordTextbox.Text, true, delegate(object data)
            {
                if (this.InvokeRequired)
                    this.Invoke(signal, data);
                else
                    signal(data);
            });
        }