public void StopCallForwarding() { Task task = CallForwardingTask; if (task == null) { Status = TwoChatsHandlerStatus.Stopped; return; } Status = TwoChatsHandlerStatus.Finishing; if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { //По идее, этот код не будет вызван никогда. SynchronizationHelper.WaitFor( () => { return(!(task.IsCanceled || task.IsCompleted || task.IsFaulted)); }, 15000 ); } else { task.Wait(15000); } BotScenario?.FinishExecution(15000); if (!(task.IsCanceled || task.IsCompleted || task.IsFaulted)) { task.Dispose(); Status = TwoChatsHandlerStatus.Aborted; } else { Status = TwoChatsHandlerStatus.Stopped; } }
public void Free() { if (IsFree) { return; } StopCallForwarding(); Chat1?.Free(); Chat1 = null; Chat2?.Free(); Chat2 = null; BotScenario?.Free(); BotScenario = null; ConversationController = null; IsFree = true; }
/// <summary> /// <para>Эта функция запускает поток, который проводит переадресацию между чатами.</para> /// <para>Очень важно понимать, что данный метод перехватит все возникающие в этом потоке ошибки и запишет их в LastException, /// включая ошибки из потока браузеров, которые по умолчанию должны были вылитеть в том потоках, а не в данном. /// </para> /// </summary> public void StartCallForwarding() { Exception lastEx = null; if (Status == TwoChatsHandlerStatus.Working) { lastEx = new Exception("Work has already began!"); } if (Status == TwoChatsHandlerStatus.FatalError) { lastEx = new Exception("Can`t start after fatal error!"); } if (Status == TwoChatsHandlerStatus.Finishing) { lastEx = new Exception("Can`t start while finishing work!"); } if (lastEx == null && !(Status == TwoChatsHandlerStatus.Stopped || Status == TwoChatsHandlerStatus.Aborted)) { lastEx = new Exception("Chat must be stopped before starting!"); } if (lastEx != null) { Status = TwoChatsHandlerStatus.FatalError; LastException = lastEx; #if DEBUG throw LastException; #endif return; } Status = TwoChatsHandlerStatus.Working; CallForwardingTask = Task.Run(() => { try { CurrentDialogNumber++; string folderWithCorrespondence = string.Format("{0}/cor_{1}", UsedFolder, CurrentDialogNumber); string correspondenceFilePath1 = folderWithCorrespondence + "/dialog1.html", correspondenceFilePath2 = folderWithCorrespondence + "/dialog2.html"; int msgCount1 = 0, msgCount2 = 0, msgCountWas1 = 0, msgCountWas2 = 0; if (Settings.SaveСorrespondence) { Directory.CreateDirectory(folderWithCorrespondence); } int loopWithoutConversation = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); long elapsedMilisecondsOnLastUpdate = 0; callbackArgs.ChatHandlerCallbackArgs1.IsRealPerson = Chat1.IsRealPerson; callbackArgs.ChatHandlerCallbackArgs2.IsRealPerson = Chat2.IsRealPerson; //throw new Exception("fok u!"); FindCompanions(); if (BotScenario != null) { if (BotScenario.IsExecuting) { throw new Exception("BotScenario is executing before start."); } ConversationController = new BotController_Conversation(callbackArgs); BotScenario.ExecuteAsync(ConversationController); } while (true) { UpdateChatsInfo(); //Get new messages msgCountWas1 = msgCount1; msgCountWas2 = msgCount2; newMsg1 = GetNewMessages(Chat1, ref msgCount1); newMsg2 = GetNewMessages(Chat2, ref msgCount2); SendMessages(Chat1, newMsg2); SendMessages(Chat2, newMsg1); //Save correspondence if (Settings.SaveСorrespondence && Directory.Exists(folderWithCorrespondence)) { SaveMessages(newMsg1, correspondenceFilePath1, 1); SaveMessages(newMsg2, correspondenceFilePath2, 2); } //If conversation was finished by chat users. if (!isTalk1 || !isTalk2) { loopWithoutConversation++; } else { loopWithoutConversation = 0; } if (loopWithoutConversation > 5) { FinishConversation(false); } //If not send messages for 60 seconds. if (stopwatch.ElapsedMilliseconds - elapsedMilisecondsOnLastUpdate > 60000) { if (msgCountWas1 == msgCount1 || msgCountWas2 == msgCount2) { FinishConversation(false); } msgCountWas1 = msgCount1; msgCountWas2 = msgCount2; elapsedMilisecondsOnLastUpdate = stopwatch.ElapsedMilliseconds; } //Check msg limit if (msgCount1 >= Settings.MessagesLimit || msgCount2 >= Settings.MessagesLimit) { FinishConversation(false); } //Check if not finished if (Status != TwoChatsHandlerStatus.Working) { break; } MakeCallback(); Thread.Sleep(50); } if (Settings.SaveСorrespondence && Directory.Exists(folderWithCorrespondence)) { int msgCount = (msgCount1 + msgCount2) / 2; HelpFuncs.MoveDirSafety(folderWithCorrespondence, folderWithCorrespondence + "__MsgCount_" + msgCount.ToString()); } } catch (Exception ex) { Status = TwoChatsHandlerStatus.FatalError; LastException = ex; } finally { if (ConversationController != null) { ConversationController.IsConversationFinished = true; } } }); }