private void button2_Click(object sender, EventArgs e) { if (!IsAuthorised()) { MessageBox.Show("尚未授权!", "BaiduMap"); return; } string bnt2Str = this.button2.Text; if (bnt2Str == "获取评论") { this.button2.Text = "暂停"; if (getCommentsthread == null) { getCommentsthread = new Thread(GetComments); getCommentsthread.IsBackground = true; getCommentsthread.Start(); } else { getCommentsthread.Resume(); } } else { this.button2.Text = "获取评论"; getCommentsthread?.Suspend(); } }
public static void Main () { bool finished = false; Thread t1 = new Thread (() => { while (!finished) {} }); Thread t2 = new Thread (() => { while (!finished) { GC.Collect (); Thread.Yield (); } }); t1.Start (); t2.Start (); Thread.Sleep (10); for (int i = 0; i < 50 * 40 * 20; ++i) { t1.Suspend (); Thread.Yield (); t1.Resume (); if ((i + 1) % (50) == 0) Console.Write ("."); if ((i + 1) % (50 * 40) == 0) Console.WriteLine (); } finished = true; t1.Join (); t2.Join (); }
public void Dispose() { thread?.Suspend(); thread = null; if (serialPort.IsOpen) { serialPort.Close(); } }
private void cmdSuspend_Click(object sender, EventArgs e) { #pragma warning disable 618 if (_visualisationThread?.ThreadState == ThreadState.WaitSleepJoin) { debugRichTextBox.Text = _visualisationThread.ThreadState.ToString(); _visualisationThread?.Suspend(); } #pragma warning restore 618 }
private void btnPause_Click(object sender, EventArgs e) { if (paused) { btnPause.Text = "Pause"; paused = false; stopwatch.Start(); checkerThread?.Resume(); } else { btnPause.Text = "Resume"; paused = true; stopwatch.Stop(); checkerThread?.Suspend(); } }
public static bool Pause() { try { if (_thread.ThreadState == ThreadState.WaitSleepJoin) { _thread?.Suspend(); return(true); } else { return(true); } } catch (Exception ex) { CallBacker.CallBackException?.Invoke(ex); return(false); } }
private void button2_Click(object sender, EventArgs e) { if (!IsAuthorised()) { MessageBox.Show("网络异常!", "Article Conversion Tool"); return; } string btnText = this.button2.Text; if (btnText == "开始") { this.button2.Text = "暂停"; folderPath = this.textBox5.Text; wordPath = this.textBox4.Text; htmPath = this.textBox6.Text; txtPath = this.textBox7.Text; if (string.IsNullOrEmpty(wordPath) || string.IsNullOrEmpty(folderPath)) { MessageBox.Show("目录不能为空!", "Article Conversion Tool"); return; } if (th2 == null) { th2 = new Thread(ReadAllWordPath); th2.IsBackground = true; th2.Start(); } else { th2?.Resume(); } } else { this.button2.Text = "开始"; th2?.Suspend(); } }
private void button1_Click(object sender, EventArgs e) { if (!IsAuthorised()) { MessageBox.Show("网络异常!", "Article Conversion Tool"); return; } string btnText = this.button1.Text; if (btnText == "开始") { this.button1.Text = "暂停"; folderPath = this.textBox1.Text; targetPath = this.textBox2.Text; if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(targetPath)) { MessageBox.Show("目录不能为空!", "Article Conversion Tool"); return; } if (th1 == null) { th1 = new Thread(ReadAllFolder); th1.IsBackground = true; th1.Start(); } else { th1?.Resume(); } } else { this.button1.Text = "开始"; th1?.Suspend(); } }
public static void SuspendPortable(this Thread thread) { thread.Suspend(); }
private void Stop_Clik(object sender, RoutedEventArgs e) { thread.Suspend(); MessageBox.Show("поток остоновлен"); }
/// <summary> /// Метод обработки закрытия формы /// Останавливает поток игры /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void End(object sender, EventArgs e) { Logger.Print("Form closed"); _gameThread.Suspend(); }
public void Stop() { _thread.Suspend(); }
// Console.WriteLine("Installed voices -"); // foreach (InstalledVoice voice in synth.GetInstalledVoices()) // { // VoiceInfo info = voice.VoiceInfo; // Console.WriteLine(" Voice Name: " + info.Name); // } // Console.WriteLine(); // Console.WriteLine("Press any key to exit..."); // Console.ReadKey(); // Changing Console Font // [DllImport("kernel32.dll", SetLastError = true)] // static extern bool SetCurrentConsoleFontEx( //IntPtr consoleOutput, //bool maximumWindow); static void Main(string[] args) { #region Variables string speakandspell; string[] Azed = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; int time = 2600; Console.CursorVisible = false; Console.OutputEncoding = System.Text.Encoding.UTF8; ConsoleColor printblack = ConsoleColor.Black; ConsoleColor printwhite = ConsoleColor.White; ConsoleColor printdarkgrey = ConsoleColor.DarkGray; ConsoleColor printlightgrey = ConsoleColor.Gray; ConsoleColor printdarkblue = ConsoleColor.DarkBlue; ConsoleColor printlightblue = ConsoleColor.Blue; ConsoleColor printlightred = ConsoleColor.Red; ConsoleColor printdarkred = ConsoleColor.DarkRed; ConsoleColor printdarkyellow = ConsoleColor.DarkYellow; ConsoleColor printlightyellow = ConsoleColor.Yellow; ConsoleColor printlightgreen = ConsoleColor.Green; ConsoleColor printdarkgreen = ConsoleColor.DarkGreen; #endregion #region StartScreen //maximizing console Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight); ShowWindow(ThisConsole, MAXIMIZE); Console.ReadKey(); //Screen.ScreenPrompt("Chapter 2"); //maximizing console // play wav //Soundz.Actor("imalive.wav"); //Soundz.Actor("mdial1.wav"); Soundz.Mdial(); // Soundz.Actor("opencmd.wav"); Soundz.OpenCmdSnd(); //Work on these lines --------------------- //CinemaHelpers.CmdConType(" Command the Console"); //CinemaHelpers.commandconsole("Command the Console"); //CinemaHelpers.CmdConWithTyping("Command the Console"); // Main Start up Screen Console.ReadKey(); // Screen.MMain(); #endregion // Initialize a new instance of the SpeechSynthesizer. SpeechSynthesizer synth = new SpeechSynthesizer(); // Configure the audio output. synth.SetOutputToDefaultAudioDevice(); //Console.WriteLine("Installed voices -"); //foreach (InstalledVoice voice in synth.GetInstalledVoices()) //{ // VoiceInfo info = voice.VoiceInfo; // Console.WriteLine(" Voice Name: " + info.Name); // Personality.Miamoto(" Voice Name: " + info.Name); // Thread.Sleep(1500); //} //Console.WriteLine(); //Console.WriteLine("Press any key to exit..."); //Console.ReadKey(); // Chapter One // #region ChapterOne // synth.Speak("An Adventure Of Switch Flippers"); // // The at symbol allows multi line strings // speakandspell = @" A silent moment passed as it was in the beginning, a quite moment, before a //sudden exceptional event proceeded again by an unfurling, an advent, a serenity //and silence.He sat in his lab as it was in the beginning and at the end; nothing has //ever been the same. // "; //synth.Speak(speakandspell); // speakandspell = "Hey Nibble"; // Personality.mybyte(speakandspell); // speakandspell = "Yeah Byte"; // Personality.nibble(speakandspell); // #endregion // ChapterOne.easteregg(); #region MovieCore #region Chapter1 MusicFx.BFire(); SpecialFx.BinaryFlood(); ChapterOne.myChapterOne(); CinemaHelpers.Timer(1000); #endregion //////nibble & byte //ChapterTwo.myChapterTwo(); //Thread.Sleep(1000); //ChapterThree.myChapterThree(); //Thread.Sleep(1000); //ChapterFour.myChapterFour(); //Thread.Sleep(1000); //ChapterFive.myChapterFive(); //Thread.Sleep(1000); //ChapterSix.myChapterSix(); //Thread.Sleep(1000); //// ch 7 and 8 work //ChapterSeven.myChapterSeven(); //Thread.Sleep(1000); //ChapterEight.myChapterEight(); //Thread.Sleep(1000); //ChapterNine.myChapterNine(); //Thread.Sleep(1000); // Console.ReadKey(); ChapterTen.myChapterTen(); Thread.Sleep(1000); Screen.Endscreen(); #region Test Region //Test //Personality.Simulus(); //Scratchpad.Scratch1(); // Scratchpad.Scratch2(); // DigitalDna.DigitalGlyph5(); Console.Write('\u2663'); // club Console.Write('\u2660'); // spade Console.Write('\u2665'); // heart Console.Write('\u2666'); //diamond // DigitalDna.DigitalGlyph6(10000); Console.ReadKey(); speakandspell = "Command Console!..... tyhcghtftycghcghfvvnhvhtytygh h ghtytyvkhgvvg5ryfyu67"; // speakandspell = "Command Console!"; //Personality.Haruka(speakandspell); //Personality.Hazel(speakandspell); //Personality.Otto(speakandspell); // CinemaHelpers.Asimbot(speakandspell); //CinemaHelpers.Asimbot(speakandspell); // CinemaHelpers.qproc(speakandspell); // Personality.MegaByte(speakandspell, "u22"); //Personality.MegaByte(speakandspell); //Personality.HelpMiamoto(speakandspell); Thread McpTao = new Thread(MusicFx.cptao); Thread staticvoidmutex = new Thread(MusicFx.staticvoidmutex); staticvoidmutex.Start(); Scratchpad.Format(speakandspell); SpecialFx.stopwatch(); Personality.FunNarrator(speakandspell); staticvoidmutex.Suspend(); Console.ReadKey(); //Thread SpfxThrob = new Thread(SpecialFx.spfxpassgenpyramid); // Thread SpfxThrob2 = new Thread(SpecialFx.spfxpassgenpyramid); // SpfxThrob.Start(); //SpecialFx.spfxpassgenpyramid(); //SpecialFx.Throbber("Thor"); // SpfxThrob2.Start(); //Screen.spfxglitchscreen(); //SpecialFx.spfxgenglitch(); //CinemaHelpers.commandconsole(speakandspell); //SpecialFx.spfxpassgenpyramid(); //SpecialFx.ScrollingDown(speakandspell); //SpecialFx.spacedscrollingflood(speakandspell); //SpecialFx.scrollingdownflood(speakandspell); //Screen.dataclouds(); //Personality.BinaryFire(speakandspell); //SpecialFx.OpenCommand(); //SpecialFx.JacktheRipper(); //SpecialFx.NumFlood(); //SpecialFx.PyramidalPrompt(1000); //SpecialFx.PyramidalPrompt(100); //SpecialFx.PromptData(); //Graphix.GraphingCalculator(); //SpecialFx.Thinking(); // Screen.ScreenPrompt("Funky"); // SpecialFx.RacingStar(); // SpecialFx.speedRacingStar(); //SpecialFx.RacingRabbit(); // SpecialFx.BackandForth(); // move to special fx //Tests.NumBurn(); // Console.CursorTop = 15; // Console.CursorLeft = 52; // Console.WriteLine("Winter has come \n"); // Console.WriteLine(); // SpecialFx.Cswatch(); // SpecialFx.AsciiTable(); // Console.WriteLine(); // Scratchpad.Format(@"-.-. //| | |, ---., ---., ---., ---., ---.. ,, . //| | || || | || || | >< | | //` ' '`---'` `---'` '`---'' ``---| // `---'"); // Console.ReadKey(); // Console.ReadKey(); // Console.CursorTop = 15; // Console.CursorLeft = 52; // Console.WriteLine("Winter has come"); // Scratchpad.Format("Try me"); // Console.ReadKey(); // SpecialFx.Throbber(" Scanning: "); // Console.ReadKey(); // Personality.nibble(@"-.-. //| | |, ---., ---., ---., ---., ---.. ,, . //| | || || | || || | >< | | //` ' '`---'` `---'` '`---'' ``---| // `---'"); // SpecialFx.splitstring(@"-.-. //| | |,---.,---.,---.,---.,---.. ,, . //| | || || | || || | >< | | //` ' '`---'` `---'` '`---'' ``---| // `---'"); // Console.ReadKey(); Soundz.Actor("schedule.wav"); Soundz.OpenCmdSnd(); Soundz.OpenCmdSnd(); Soundz.Mdial(); Soundz.Actor("ring.wav"); SpecialFx.splitstring(speakandspell); SpecialFx.splitstring(" DDDDDDDDDF FEFEE FFFFFFFFFFFF EEEEEEEE GGGGGGGGG"); SpecialFx.ScreenTyper(" DDDDDDDDDF FEFEE FFFFFFFFFFFF EEEEEEEE GGGGGGGGG"); //SpecialFx.stringtonum("hello world"); Console.Write('\u2103'); Console.Write('\u058D'); Console.Write('\u2116'); Console.Write('\u2620'); Console.Write('\u0169'); Console.Write('\u4042'); // card suits Console.Write('\u2663'); Console.Write('\u2660'); Console.Write('\u2665'); Console.Write('\u2666'); #endregion #endregion //Console.WriteLine("Installed voices -"); //foreach (InstalledVoice voice in synth.GetInstalledVoices()) //{ // VoiceInfo info = voice.VoiceInfo; // Console.WriteLine(" Voice Name: " + info.Name); //} Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static void Main() { // Get the current thread and set its name. Thread.CurrentThread.Name = "Main Thread"; // Create an instance of the ThreadedClass. ThreadedClass tc1 = new ThreadedClass("Thread1"); // Set the ThreadedClass's boolean internal suspend call to true. tc1.InternalSuspendCall = true; // Create the thread giving it the delegate with the // method that should be called when the thread starts. Console.WriteLine ("Main - Creating thread t1."); Thread t1 = new Thread(tc1.ThreadMethod); t1.Name = "T1 Worker Thread"; // Start the thread t1.Start(); Console.WriteLine ("Main - t1 thread started."); // Sleep for a few seconds. Console.WriteLine("Main - Sleeping for 5 seconds."); Thread.Sleep (5000); // Start another thread ThreadedClass tc2 = new ThreadedClass("Thread2"); tc2.InternalSuspendCall = false; Thread t2 = new Thread(tc2.ThreadMethod); t2.Name = "T2 Worker Thread"; t2.Start(); Console.WriteLine ("Main - t2 thread started."); // Resume the first thread. Console.WriteLine ("Main - Resuming t1 from Suspend() call."); t1.Resume(); // Pause the second thread. Console.WriteLine ("Main - Calling Suspend() on t2."); // *** For some reason, I occasionally see this program hang here when not debugging. t2.Suspend(); // This may throw an exception if t2 is not running. Console.WriteLine ("Main - Thread t2 is now suspended."); // Wait a moment. Console.WriteLine("Main - Sleeping for 5 seconds."); Thread.Sleep(5000); // Resume the second thread. Console.WriteLine ("Main - Resuming t2 from Suspend() call."); t2.Resume(); // Wait a moment. Console.WriteLine("Main - Sleeping for 5 seconds."); Thread.Sleep(5000); // Pause the program. Usually, this message will appear // before the message from the threaded method appears. Console.Write ("Main - Press <ENTER> to end: "); Console.ReadLine(); }
public static void Send(String dataToSend) { if (!initialized) { Initialize(); } if (initialized && SettingsForm.NetworkBit) { try { if (dstToSendAddress != null) { CurrentState = NetworkState.Sending; if (receiveThread != null) { receiveThread.Suspend(); } if (udpClient != null) { udpClient.Close(); } udpClient = new UdpClient(udpPort); if (hardPlay && Program.godmode) { dataToSend = "Hard;" + dataToSend; } else { dataToSend = "Normal;" + dataToSend; } Byte[] sendBytes = Encoding.ASCII.GetBytes(dataToSend.ToString()); byte endDstIP = dstToSendAddress.GetAddressBytes()[3]; byte broadcastEndIp = 255; if (endDstIP == broadcastEndIp && Program.godmode == false) { return; } if (Program.debugmode) { Console.WriteLine("Sending \n" + dataToSend + "\n to " + ConvertFromIP(dstToSendAddress.Address) + "..."); } udpClient.Send(sendBytes, sendBytes.Length, new IPEndPoint(dstToSendAddress, udpPort)); if (Program.debugmode) { Console.WriteLine("Sent."); } udpClient.Close(); CurrentState = NetworkState.Receiving; StartReceiving(); } } catch (Exception e) { if (Program.debugmode) { Console.WriteLine("Exception in: Send(..)\n" + e.ToString()); } } } }
/// <summary> /// Handles the touch up event. /// </summary> /// <param name="e">Touch event arguments.</param> /// <returns>Touch event arguments.</returns> public override TouchEventArgs OnTouchUp(TouchEventArgs e) { if (_calibrating) { Settings.CX[_currentCalPoint] = (short)e.Point.X; Settings.CY[_currentCalPoint] = (short)e.Point.Y; if (_currentCalPoint == Settings.Points.Length - 1) { _calibrating = false; _canvas.Clear(); Invalidate(); _text1.FontColor = Colors.Blue; _text1.Visible = true; Thread.Sleep(250); Touch.ActiveTouchPanel.SetCalibration(Settings.Points.Length, Settings.SX, Settings.SY, Settings.CX, Settings.CY); GlideTouch.Calibrated = true; _thread = new Thread(Countdown); _thread.Priority = ThreadPriority.AboveNormal; _thread.Start(); _exitBtn.Visible = true; _startBtn.Visible = true; ModalResult result = ModalResult.Yes; //Glide.MessageBoxManager.Show(String.Empty, "Calibration Complete", ModalButtons.YesNo); try { _thread.Suspend(); _thread = null; } catch { } if (result == ModalResult.Yes) { if (_autoSave) { GlideTouch.SaveCalibration(Settings); _text1.Text = "Calibration set and saved."; } else { _text1.Text = "Calibration set but not saved."; } Thread.Sleep(1000); TriggerCloseEvent(this); } else { if (GlideTouch.CalSettings != null) { Touch.ActiveTouchPanel.SetCalibration(Settings.Points.Length, Settings.SX, Settings.SY, Settings.CX, Settings.CY); _text1.Text = "Calibration reverted to previous settings."; } else { _text1.Text = "Calibration remains set. Cannot revert; previous settings do not exist."; } } FillRect(_text1.Rect); _text1.Invalidate(); } else { _currentCalPoint++; DrawCrossHair(Settings.Points[_currentCalPoint].X, Settings.Points[_currentCalPoint].Y); } } return(base.OnTouchUp(e)); }
private void button2_Click(object sender, EventArgs e) { L.Suspend(); MessageBox.Show("ПОТОК ПРИОСТАНОВЛЕН"); }
public void ShutDownClient() { refreshThread.Suspend(); serverHandling.Shutdown(); }
/// <summary> /// The function that does all of the work /// TODO: Factor some nice methods out of here; this is just garbage to read right now /// </summary> public static void SynchronizationThread() { SyncServiceAddin addin = null; SyncServer server = null; try { addin = GetConfiguredSyncService(); if (addin == null) { SetState(SyncState.NoConfiguredSyncService); Logger.Debug("GetConfiguredSyncService is null"); SetState(SyncState.Idle); syncThread = null; return; } Logger.Debug("SyncThread using SyncServiceAddin: {0}", addin.Name); SetState(SyncState.Connecting); try { server = addin.CreateSyncServer(); if (server == null) { throw new Exception("addin.CreateSyncServer () returned null"); } } catch (Exception e) { SetState(SyncState.SyncServerCreationFailed); Logger.Error("Exception while creating SyncServer: {0}\n{1}", e.Message, e.StackTrace); SetState(SyncState.Idle); syncThread = null; addin.PostSyncCleanup(); // TODO: Needed? return; // TODO: Figure out a clever way to get the specific error up to the GUI } // TODO: Call something that processes all queued note saves! // For now, only saving before uploading (not sufficient for note conflict handling) SetState(SyncState.AcquiringLock); // TODO: We should really throw exceptions from BeginSyncTransaction () if (!server.BeginSyncTransaction()) { SetState(SyncState.Locked); Logger.Warn("PerformSynchronization: Server locked, try again later"); SetState(SyncState.Idle); syncThread = null; addin.PostSyncCleanup(); return; } Logger.Debug("8"); int latestServerRevision = server.LatestRevision; int newRevision = latestServerRevision + 1; // If the server has been wiped or reinitialized by another client // for some reason, our local manifest is inaccurate and could misguide // sync into erroneously deleting local notes, etc. We reset the client // to prevent this situation. string serverId = server.Id; if (client.AssociatedServerId != serverId) { client.Reset(); client.AssociatedServerId = serverId; } SetState(SyncState.PrepareDownload); // Handle notes modified or added on server Logger.Debug("Sync: GetNoteUpdatesSince rev " + client.LastSynchronizedRevision.ToString()); IDictionary <string, NoteUpdate> noteUpdates = server.GetNoteUpdatesSince(client.LastSynchronizedRevision); Logger.Debug("Sync: " + noteUpdates.Count + " updates since rev " + client.LastSynchronizedRevision.ToString()); // Gather list of new/updated note titles // for title conflict handling purposes. List <string> noteUpdateTitles = new List <string> (); foreach (NoteUpdate noteUpdate in noteUpdates.Values) { if (!string.IsNullOrEmpty(noteUpdate.Title)) { noteUpdateTitles.Add(noteUpdate.Title); } } // First, check for new local notes that might have title conflicts // with the updates coming from the server. Prompt the user if necessary. // TODO: Lots of searching here and in the next foreach... // Want this stuff to happen all at once first, but // maybe there's a way to store this info and pass it on? foreach (NoteUpdate noteUpdate in noteUpdates.Values) { if (FindNoteByUUID(noteUpdate.UUID) == null) { Note existingNote = NoteMgr.Find(noteUpdate.Title); if (existingNote != null && !noteUpdate.BasicallyEqualTo(existingNote)) { // Logger.Debug ("Sync: Early conflict detection for '{0}'", noteUpdate.Title); if (syncUI != null) { syncUI.NoteConflictDetected(NoteMgr, existingNote, noteUpdate, noteUpdateTitles); // Suspend this thread while the GUI is presented to // the user. syncThread.Suspend(); } } } } if (noteUpdates.Count > 0) { SetState(SyncState.Downloading); } // TODO: Figure out why GUI doesn't always update smoothly // Process updates from the server; the bread and butter of sync! foreach (NoteUpdate noteUpdate in noteUpdates.Values) { Note existingNote = FindNoteByUUID(noteUpdate.UUID); if (existingNote == null) { // Actually, it's possible to have a conflict here // because of automatically-created notes like // template notes (if a note with a new tag syncs // before its associated template). So check by // title and delete if necessary. existingNote = NoteMgr.Find(noteUpdate.Title); if (existingNote != null) { Logger.Debug("SyncManager: Deleting auto-generated note: " + noteUpdate.Title); DeleteNoteInMainThread(existingNote); } CreateNoteInMainThread(noteUpdate); } else if (existingNote.MetadataChangeDate.CompareTo(client.LastSyncDate) <= 0 || noteUpdate.BasicallyEqualTo(existingNote)) { // Existing note hasn't been modified since last sync; simply update it from server UpdateNoteInMainThread(existingNote, noteUpdate); } else { // Logger.Debug ("Sync: Late conflict detection for '{0}'", noteUpdate.Title); Logger.Debug(string.Format( "SyncManager: Content conflict in note update for note '{0}'", noteUpdate.Title)); // Note already exists locally, but has been modified since last sync; prompt user if (syncUI != null) { syncUI.NoteConflictDetected(NoteMgr, existingNote, noteUpdate, noteUpdateTitles); // Suspend this thread while the GUI is presented to // the user. syncThread.Suspend(); } // Note has been deleted or okay'd for overwrite existingNote = FindNoteByUUID(noteUpdate.UUID); if (existingNote == null) { CreateNoteInMainThread(noteUpdate); } else { UpdateNoteInMainThread(existingNote, noteUpdate); } } } // Note deletion may affect the GUI, so we have to use the // delegate to run in the main gtk thread. // To be consistent, any exceptions in the delgate will be caught // and then rethrown in the synchronization thread. GuiUtils.GtkInvokeAndWait(() => { // Make list of all local notes List <Note> localNotes = new List <Note> (NoteMgr.Notes); // Get all notes currently on server IList <string> serverNotes = server.GetAllNoteUUIDs(); // Delete notes locally that have been deleted on the server foreach (Note note in localNotes) { if (client.GetRevision(note) != -1 && !serverNotes.Contains(note.Id)) { if (syncUI != null) { syncUI.NoteSynchronized(note.Title, NoteSyncType.DeleteFromClient); } NoteMgr.Delete(note); } } }); // TODO: Add following updates to syncDialog treeview SetState(SyncState.PrepareUpload); // Look through all the notes modified on the client // and upload new or modified ones to the server List <Note> newOrModifiedNotes = new List <Note> (); foreach (Note note in new List <Note> (NoteMgr.Notes)) { if (client.GetRevision(note) == -1) { // This is a new note that has never been synchronized to the server // TODO: *OR* this is a note that we lost revision info for!!! // TODO: Do the above NOW!!! (don't commit this dummy) note.Save(); newOrModifiedNotes.Add(note); if (syncUI != null) { syncUI.NoteSynchronized(note.Title, NoteSyncType.UploadNew); } } else if (client.GetRevision(note) <= client.LastSynchronizedRevision && note.MetadataChangeDate > client.LastSyncDate) { note.Save(); newOrModifiedNotes.Add(note); if (syncUI != null) { syncUI.NoteSynchronized(note.Title, NoteSyncType.UploadModified); } } } Logger.Debug("Sync: Uploading " + newOrModifiedNotes.Count.ToString() + " note updates"); if (newOrModifiedNotes.Count > 0) { SetState(SyncState.Uploading); server.UploadNotes(newOrModifiedNotes); // TODO: Callbacks to update GUI as upload progresses } // Handle notes deleted on client List <string> locallyDeletedUUIDs = new List <string> (); foreach (string noteUUID in server.GetAllNoteUUIDs()) { if (FindNoteByUUID(noteUUID) == null) { locallyDeletedUUIDs.Add(noteUUID); if (syncUI != null) { string deletedTitle = noteUUID; if (client.DeletedNoteTitles.ContainsKey(noteUUID)) { deletedTitle = client.DeletedNoteTitles [noteUUID]; } syncUI.NoteSynchronized(deletedTitle, NoteSyncType.DeleteFromServer); } } } if (locallyDeletedUUIDs.Count > 0) { SetState(SyncState.DeleteServerNotes); server.DeleteNotes(locallyDeletedUUIDs); } SetState(SyncState.CommittingChanges); bool commitResult = server.CommitSyncTransaction(); if (commitResult) { // Apply this revision number to all new/modified notes since last sync // TODO: Is this the best place to do this (after successful server commit) foreach (Note note in newOrModifiedNotes) { client.SetRevision(note, newRevision); } SetState(SyncState.Succeeded); } else { SetState(SyncState.Failed); // TODO: Figure out a way to let the GUI know what exactly failed } // This should be equivalent to newRevision client.LastSynchronizedRevision = server.LatestRevision; client.LastSyncDate = DateTime.Now; Logger.Debug("Sync: New revision: {0}", client.LastSynchronizedRevision); SetState(SyncState.Idle); } catch (Exception e) { // top-level try Logger.Error("Synchronization failed with the following exception: " + e.Message + "\n" + e.StackTrace); // TODO: Report graphically to user try { SetState(SyncState.Idle); // stop progress SetState(SyncState.Failed); SetState(SyncState.Idle); // required to allow user to sync again if (server != null) { // TODO: All I really want to do here is cancel // the update lock timeout, but in most cases // this will delete lock files, too. Do better! server.CancelSyncTransaction(); } } catch {} } finally { syncThread = null; try { addin.PostSyncCleanup(); } catch (Exception e) { Logger.Error("Error cleaning up addin after sync: " + e.Message + "\n" + e.StackTrace); } } }
/*** EcouteImages * Ecoute le socket data pour récupérer les fragments et les aggréger en images ***/ protected void EcouteImages() { bool premier_fragment = true; // Indique s'il on est sur le premier fragment int image_actuelle = 0; // Le numéro de l'image actuelle int numImage = 0; // Le numéro de l'image que l'on vient de lire int tailleImage = 0; // La taille de l'image int tailleFragment = 0; // Taille du fragment (entete) int positionPaquet = 0; // La position du paquet dans l'image string entete = ""; // Les entetes int numPremierOctetDonnee; // Début des bytes de l'image dans le fragment int numParam; // le nombre de paramètres char c; // un char tout bête pour faire une conversion char à char string[] parametres = new string[5]; //les parametres de l'image byte[] image = null; // Tableau contenant les octets representant l'image byte[] fragment = new byte[tailleFragmentTheorique]; // le fragment que l'on va recevoir // Connection du socket if (socket_data == null) { socket_data = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket_data.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1); socket_data.Bind(ep); } // On boucle sur la lecture des images (en fragments) for (; ;) { socket_data.ReceiveFrom(fragment, ref ep); // Transformation du byte[] en string numPremierOctetDonnee = 0; numParam = 0; entete = ""; do { c = (char)fragment[numPremierOctetDonnee]; if (c == '\r') { numPremierOctetDonnee++; numParam++; } entete += c; numPremierOctetDonnee++; } while (numParam < 4); // On récupère les données concernant l'image parametres = entete.Split(new char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries); numImage = int.Parse(parametres[0]); tailleImage = int.Parse(parametres[1]); positionPaquet = int.Parse(parametres[2]); tailleFragment = int.Parse(parametres[3]); if (premier_fragment) { image_actuelle = numImage; } // Si on change d'image if (image_actuelle != numImage) { // On sauvegarde l'image Image imageActuelle = System.Drawing.Image.FromStream(new MemoryStream(image)); // Si le buffer d'image est plein, on s'arrête if (lesImages.Count == bufferSize) { monThread.Suspend(); } // On empile l'image lesImages.Enqueue(imageActuelle); // On ajoute aux stats une nouvelle image if (startTime != DateTime.MinValue) { TimeSpan time = DateTime.Now.Subtract(startTime); mesStats.IncrementReceivedImages(time.TotalMilliseconds, tailleImage); } else { mesStats.IncrementReceivedImages(); } // Le redémarre le compteur. startTime = DateTime.Now; while (mesStats.getNumberOfImages() < numImage) { mesStats.IncrementLooseImages(); } // On met à jour notre numéro d'image image_actuelle = numImage; premier_fragment = true; } if (premier_fragment) { // On crée le tableau d'octets qui va recevoir l'image image = new byte[tailleImage]; premier_fragment = false; } // On stocke le fragment dans le tableau représentant l'image for (int i = 0; i < tailleFragment; i++) { image[positionPaquet + i] = fragment[numPremierOctetDonnee + i]; } } }
private void button2_Click(object sender, EventArgs e) { Serial_port.Suspend(); port.WriteLine("2,0"); Serial_port.Resume(); }
protected void Tick() { double qtVal = quantum.Value; while (true) { Thread.Sleep(1000); if (kind == 'F') { Gtk.TreeIter iter; ProcessList.GetIterFirst(out iter); string time = ProcessList.GetValue(iter, 1).ToString(); int newTime = int.Parse(time) - 1; CPU.Fraction -= step; if (newTime == 0) { ProcessList.Remove(ref iter); Process p = processListControl[0]; processListControl.RemoveAt(0); p.Button.Visible = true; GetCancelButton(p.Button).Visible = false; RAMSpace.Fraction -= (double)p.Size / 1024; RAMSpace.Text = (int.Parse(RAMSpace.Text.Split('/')[0]) - p.Size).ToString() + "/820 (1024) MB"; TryFit(); if (ProcessList.IterNChildren() == 0) { RAMTicker.Suspend(); } else { CPU.Fraction = 1; ProcessList.GetIterFirst(out iter); string nextTime = ProcessList.GetValue(iter, 1).ToString(); step = 1 / double.Parse(nextTime); } continue; } ProcessList.SetValue(iter, 1, newTime.ToString()); } else if (kind == 'R') { Gtk.TreeIter iter; ProcessList.GetIterFirst(out iter); Process p = processListControl[0]; string time = ProcessList.GetValue(iter, 1).ToString(); if (qtVal > 0) { int newTime = int.Parse(time) - 1; CPU.Fraction -= step; p.Percentage -= step; qtVal--; if (newTime == 0) { processListControl.RemoveAt(0); ProcessList.Remove(ref iter); p.Button.Visible = true; GetCancelButton(p.Button).Visible = false; RAMSpace.Fraction -= (double)p.Size / 1024; RAMSpace.Text = (int.Parse(RAMSpace.Text.Split('/')[0]) - p.Size).ToString() + "/820 (1024) MB"; TryFit(); qtVal = quantum.Value; if (ProcessList.IterNChildren() == 0) { frmQuantum.Sensitive = true; RAMTicker.Suspend(); } else { p = processListControl[0]; CPU.Fraction = p.Percentage; ProcessList.GetIterFirst(out iter); string nextTime = ProcessList.GetValue(iter, 1).ToString(); step = p.Percentage / double.Parse(nextTime); } continue; } ProcessList.SetValue(iter, 1, newTime.ToString()); } else { qtVal = quantum.Value; string process = ProcessList.GetValue(iter, 0).ToString(); string size = ProcessList.GetValue(iter, 2).ToString(); ProcessList.Remove(ref iter); ProcessList.InsertWithValues(ProcessList.IterNChildren(), process, time, size); if (processListControl.Count > 1) { processListControl.Add(processListControl[0]); processListControl.RemoveAt(0); } if (ProcessList.IterNChildren() == 0) { frmQuantum.Sensitive = true; RAMTicker.Suspend(); } else { ProcessList.GetIterFirst(out iter); string nextTime = ProcessList.GetValue(iter, 1).ToString(); p = processListControl[0]; CPU.Fraction = p.Percentage; step = p.Percentage / double.Parse(nextTime); } } } } }
public void Run() { Thread tA = new Thread( new ThreadStart( ThreadA ) ); Thread tB = new Thread( new ThreadStart( ThreadB ) ); Thread.CurrentThread.Name = "Main thread"; tA.Name = "Thread A"; tB.Name = "Thread B"; tA.Start(); tB.Start(); System.Console.WriteLine( "Suspending thread A" ); Thread.Sleep( 100 ); tA.Suspend(); Thread.Sleep( 2500 ); System.Console.WriteLine( "Suspending thread B" ); tB.Suspend(); Thread.Sleep( 2500 ); System.Console.WriteLine( "Running GC..." ); GC.Collect(); System.Console.WriteLine( "Suspending main thread" ); Thread.Sleep( 2500 ); tA.Resume(); _mreA.Set(); Thread.Sleep( 2500 ); tB.Resume(); _mreB.Set(); }
private void button2_Click(object sender, EventArgs e) { listen.Suspend(); // Application.Exit(); }
private void button2_Click(object sender, EventArgs e) { t.Suspend(); }
private void GetIndicadores(string _jefa, DateTime _fi, DateTime _ff, string _sucursal) { try { this.Esperar(); using (SqlConnection conn = new SqlConnection(ClasesSGUV.Propiedades.conectionSGUV)) { using (SqlCommand command = new SqlCommand("PJ_IndicadoresCobranza", conn)) { conn.Open(); command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = 0; command.Parameters.AddWithValue("@TipoConsulta", 1); command.Parameters.AddWithValue("@Sucursales", _sucursal); command.Parameters.AddWithValue("@JefaCobranza", _jefa); command.Parameters.AddWithValue("@FechaInicial", _fi); command.Parameters.AddWithValue("@FechaFinal", _ff); command.Parameters.AddWithValue("@Sucursal", string.Empty); DataTable table = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = command; adapter.Fill(table); decimal objetivo = 0; decimal cobranza = 0; var qryObjetivo = (from iObj in table.AsEnumerable() where iObj.Field <string>("Indicador") == "[1]" select iObj).ToList(); if (qryObjetivo.Count() > 0) { objetivo = Convert.ToDecimal(qryObjetivo[0].ItemArray[1]); txtObjetivo.Text = Convert.ToDecimal(qryObjetivo[0].ItemArray[1]).ToString(qryObjetivo[0].ItemArray[2].ToString()); } var qryCobranza = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[2]" select item).ToList(); if (qryCobranza.Count() > 0) { cobranza = Convert.ToDecimal(qryCobranza[0].ItemArray[1]); txtCobranza.Text = Convert.ToDecimal(qryCobranza[0].ItemArray[1]).ToString(qryCobranza[0].ItemArray[2].ToString()); } txtCobranzavsObjetivoM.Text = (cobranza - objetivo).ToString("C2"); txtCobranzavsObjetivoM.ForeColor = this.Colores(txtCobranzavsObjetivoM, cobranza - objetivo, true, img1Up, img1Down); txtCobranzavsObjetivoP.ForeColor = this.Colores(txtCobranzavsObjetivoP, cobranza - objetivo, true, img2Up, img2Down); if (objetivo != 0) { txtCobranzavsObjetivoP.Text = (cobranza / objetivo).ToString("P2"); } else { txtCobranzavsObjetivoP.Text = "0%"; } var qryPronosticoM = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[3]" select item).ToList(); if (qryPronosticoM.Count() > 0) { txtPronosticoM.Text = Convert.ToDecimal(qryPronosticoM[0].ItemArray[1]).ToString(qryPronosticoM[0].ItemArray[2].ToString()); } var qryPronosticoP = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[4]" select item).ToList(); if (qryPronosticoP.Count() > 0) { txtPronosticoP.Text = Convert.ToDecimal(qryPronosticoP[0].ItemArray[1]).ToString(qryPronosticoP[0].ItemArray[2].ToString()); } //cartera vencida mes anterior var qryCarteraVM = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[11]" select item).ToList(); if (qryCarteraVM.Count() > 0) { CarteraAM = Convert.ToDecimal(qryCarteraVM[0].ItemArray[1]); txtCarteraAnteriorM.Text = Convert.ToDecimal(qryCarteraVM[0].ItemArray[1]).ToString(qryCarteraVM[0].ItemArray[2].ToString()); } var qryCarteraVP = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[12]" select item).ToList(); if (qryCarteraVP.Count() > 0) { CarteraAP = Convert.ToDecimal(qryCarteraVP[0].ItemArray[1]); txtCarteraAnteriorP.Text = Convert.ToDecimal(qryCarteraVP[0].ItemArray[1]).ToString(qryCarteraVP[0].ItemArray[2].ToString()); } //cartera vencida actual var qryCarteraM = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[5]" select item).ToList(); if (qryCarteraM.Count() > 0) { CarteraHM = Convert.ToDecimal(qryCarteraM[0].ItemArray[1]); txtCarteraM.Text = Convert.ToDecimal(qryCarteraM[0].ItemArray[1]).ToString(qryCarteraM[0].ItemArray[2].ToString()); } var qryCarteraP = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[6]" select item).ToList(); if (qryCarteraP.Count() > 0) { CarteraHP = Convert.ToDecimal(qryCarteraP[0].ItemArray[1]); txtCarteraP.Text = Convert.ToDecimal(qryCarteraP[0].ItemArray[1]).ToString(qryCarteraP[0].ItemArray[2].ToString()); } txtDif2.Text = (CarteraHP - CarteraAP).ToString("P2"); txtDif1.Text = (CarteraHM - CarteraAM).ToString("C2"); //txtDif2.Text = //----------------------------------------------------------- var qryDiasCartera = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[7]" select item).ToList(); decimal DiasCartera = 0; if (qryDiasCartera.Count() > 0) { DiasCartera = Convert.ToDecimal(qryDiasCartera[0].ItemArray[1]); txtDiasCartera.Text = DiasCartera.ToString(qryDiasCartera[0].ItemArray[2].ToString()); } var qryNCPendientes = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[8]" select item).ToList(); decimal factsPen = 0; if (qryNCPendientes.Count() > 0) { factsPen = Convert.ToDecimal(qryNCPendientes[0].ItemArray[1]); txtNotasSaldo.Text = Convert.ToDecimal(qryNCPendientes[0].ItemArray[1]).ToString(qryNCPendientes[0].ItemArray[2].ToString()); } var qryFacturasMes = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[9]" select item).ToList(); if (qryFacturasMes.Count() > 0) { decimal facts = Convert.ToDecimal(qryFacturasMes[0].ItemArray[1]); if (facts > 0) { tct.Text = (factsPen / Convert.ToDecimal(qryFacturasMes[0].ItemArray[1])).ToString(qryFacturasMes[0].ItemArray[2].ToString()); } } ////-------- var qryCV = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[13]" select item).ToList(); decimal OCV = 0; if (qryCV.Count() > 0) { OCV = Convert.ToDecimal(qryCV[0].ItemArray[1]); txtObjCartera.Text = OCV.ToString(qryCV[0].ItemArray[2].ToString()); } txtDiferenciaCV.Text = (CarteraHP - OCV).ToString("P2"); var qryDC = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[14]" select item).ToList(); decimal ODC = 0; if (qryDC.Count() > 0) { ODC = Convert.ToDecimal(qryDC[0].ItemArray[1]); txtObjDC.Text = ODC.ToString(qryDC[0].ItemArray[2].ToString()); } txtDifDC.Text = (DiasCartera - ODC).ToString("N0"); txtDifDC.ForeColor = this.Colores(txtDifDC, DiasCartera - ODC, false, img5Up, img5Down); txtDiferenciaCV.Text = (CarteraHP - OCV).ToString("P2"); txtDiferenciaCV.ForeColor = this.Colores(txtDiferenciaCV, CarteraHP - OCV, false, img4Up, img4Down); ////////------- var qryCompromisos = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[10]" select item).ToList(); var qryEC = (from item in table.AsEnumerable() where item.Field <string>("Indicador") == "[15]" select item).ToList(); decimal OEC = 0; if (qryEC.Count() > 0) { OEC = Convert.ToDecimal(qryEC[0].ItemArray[1]); txtEdoCta.Text = OEC.ToString(qryEC[0].ItemArray[2].ToString()); } if (qryCompromisos.Count() > 0) { decimal facts = Convert.ToDecimal(qryCompromisos[0].ItemArray[1]); toolTip1.SetToolTip(btnCompromisos, facts.ToString("N0") + " Compromisos vencen hoy!"); if (facts > 0) { btnCompromisos.Enabled = true; if (h.ThreadState == ThreadState.Unstarted) { h.Start(); } else if (h.ThreadState == ThreadState.Suspended) { h.Resume(); } } else { btnCompromisos.Enabled = false; if (h.IsAlive) { h.Suspend(); } btnCompromisos.BackColor = Color.FromName("Info"); btnCompromisos.ForeColor = Color.Black; } } } } btnDetalle.Enabled = true; } catch (Exception) { } finally { this.Continuar(); } }
public static void DesconectarServidor() { ibConectado = false; TheadUDP.Suspend(); udpServer.Close(); }
/// <summary>Pauses updating the clock</summary> public void Pause() { try { AsyncThread?.Suspend(); } catch { } } //I know these are obsolete but mira, the whole reason they are is because of resource protection.
private static StackTrace GetStackTrace(Thread thread) { bool suspended = false; try { thread.Suspend(); suspended = true; return new StackTrace(thread, true); } catch (ThreadStateException) { return null; //we missed this one } finally { if (suspended) { thread.Resume(); } } }
public static void Main(string[] args) { Console.Write("Diga o nome do arquivo de img: "); string nomeArq = Console.ReadLine(); Console.Write("Diga o tamanho do embacamento: "); int coef = Int32.Parse(Console.ReadLine()); Image imagem = Image.FromFile(nomeArq); Bitmap bitmap = new Bitmap(imagem); Console.Write("Quantas thread horizontais? "); int threadsH = Int32.Parse(Console.ReadLine()); Console.Write("Quantas thread verticais? "); int threadsV = Int32.Parse(Console.ReadLine()); totalThreads = threadsH * threadsV; ThreadEmb[,] threads = new ThreadEmb[threadsV, threadsH]; int i, j; int qtdX = bitmap.Width / threadsH; int qtdY = bitmap.Height / threadsV; Graphics g = Graphics.FromImage(bitmap); for (i = 0; i < threadsV; i++) { for (j = 0; j < threadsH; j++) { threads[i, j] = new ThreadEmb((Bitmap)bitmap.Clone(), coef, qtdX * j, qtdX, qtdY * i, qtdY, i, j); } } Thread t; ThreadStart ts; threadPrincipal = Thread.CurrentThread; for (i = 0; i < threadsV; i++) { for (j = 0; j < threadsH; j++) { ts = new ThreadStart(threads[i, j].Iniciar); t = new Thread(ts); t.Start(); } } //while (threadCompletas < totalThreads) { } threadPrincipal.Suspend(); for (i = 0; i < threadsV; i++) { for (j = 0; j < threadsH; j++) { threads[i, j].desenhaResultado(g); } } bitmap.Save("editado_" + nomeArq); }
static void Main(string[] args) { Console.WriteLine("ЗАДАНИЕ 1"); //работаем с процессами//запущенные процессы foreach (Process pr in Process.GetProcesses()) { Console.WriteLine("Имя процесса: " + pr.ProcessName + " Приоритет: " + pr.BasePriority + /*" Время запуска: " + pr.StartTime + */ " Состояние: " + pr.Responding + /*" Использование времени процессора: " + pr.PrivilegedProcessorTime*/ " ID: " + pr.Id); } Console.WriteLine("\nЗАДАНИЕ 2"); // исследуем текущий домен Console.WriteLine("исследуем текущий домен"); AppDomain domain = AppDomain.CurrentDomain; //cto takoye domen? Console.WriteLine("Name: " + domain.FriendlyName); //imya domena Console.WriteLine("Directory: " + domain.BaseDirectory); //? foreach (Assembly a in domain.GetAssemblies()) //sborki domena { Console.WriteLine(a.GetName().Name); } //создаем домен, загружаем туда сборку, выгружаем домен Console.WriteLine("создаем домен, загружаем туда сборку, выгружаем домен"); AppDomain secdomain = AppDomain.CreateDomain("Second Domain"); //sozdaem secdomain.Load(new AssemblyName("laba 15")); //zagrujaem nashu sborku Console.WriteLine("Name: " + secdomain.FriendlyName); //imya domena foreach (Assembly a in secdomain.GetAssemblies()) //vyvodim vse sborki { Console.WriteLine(a.GetName().Name); } AppDomain.Unload(secdomain);//vygrujaem domena Console.WriteLine("\nЗАДАНИЕ 3"); //работаем с потоками Console.WriteLine("Введите n: "); int n = int.Parse(Console.ReadLine()); Thread mythread = new Thread(new ParameterizedThreadStart(ToConsoleFile));//делегат threadstart mythread.Start(n); mythread.Name = "MyThread00"; Console.WriteLine("Поток: " + mythread.Name + " Состояние: " + mythread.ThreadState + " Приоритет: " + mythread.Priority); for (int i = 1; i <= n; i++) { Console.WriteLine("Главный поток: " + i); //glavnyy potok eto main Thread.Sleep(500); //priostanavlivaem glavn potok na 500millisekunt mythread.Suspend(); //priostanavlivaem nash potok } mythread.Resume(); //kak zakoncirsya gl potok , nash potok vozobnavlyaetsya Console.WriteLine("ЗАДАНИЕ 4"); Console.WriteLine("Введите x: "); int x = int.Parse(Console.ReadLine()); using (FileStream fs = new FileStream(oshfile.ToString(), FileMode.Create, FileAccess.Write)) { } Thread first = new Thread(new ParameterizedThreadStart(Chet));//thread-sazdaet potok Thread second = new Thread(new ParameterizedThreadStart(Nechet)); second.Priority = ThreadPriority.Highest;//Поменяйте приоритет одного из потоков. Console.WriteLine("приоритет второго потока : "); Console.WriteLine(second.Priority); Console.WriteLine("приоритет первого потока :"); Console.WriteLine(first.Priority); //последовательно выводились одно четное, другое нечетное. first.Start(x); second.Start(x); Console.WriteLine("ЗАДАНИЕ 5"); Console.WriteLine("Введите количество секунд(таймер): "); int ch; ch = int.Parse(Console.ReadLine()); /////////////////////////////////////////////////////////////////////////////////////// TimerCallback tm = new TimerCallback(TimerSec); // метод обратного вызова Timer tmr = new Timer(tm, ch, 500, 1000); Thread.Sleep(ch * 10000); tmr.Dispose(); Console.ReadKey(); }
private void pauseButton_Click(object sender, EventArgs e) { chipThread.Suspend(); soundThread.Suspend(); }
public void ThreadSuspend() { th.Suspend(); Console.WriteLine("Thread suspended!"); }
private void AbortTest12( ) { Console.WriteLine("AT12:Start Test"); ThreadStart ts = new ThreadStart(this.Abortee12); Thread t = new Thread(ts); t.Start( ); Delay(500); Console.WriteLine("AT12:suspending t1"); t.Suspend( ); Delay(50000); }
static void Main(string[] args) { //Generate the device ID of this end Random devIDgen = new Random(); devID = (ushort)devIDgen.Next(0x0000, 0xFFFF); deviceData = String.Format("{0:X}", devID) + "," + noSignalStr; //List current COM ports Console.WriteLine("Currently Open COM ports:"); String[] currCOMS = SerialPort.GetPortNames(); for (int i = 0; i < currCOMS.Length; i++) { Console.Write(currCOMS[i] + ","); } Console.WriteLine(); //Initial GPS data read test Console.WriteLine("Enter the port number for the GPS below"); //Get the port number from the user String portNumber = Console.ReadLine(); GPSin = new SerialPort(portNumber, 4800, Parity.None, 8); //Initialize the serial port for the GPS GPSin.Open(); //Open the port to communicate with the GPS Console.WriteLine("Enter the port number for the ALT5801 Wireless transceiver below"); portNumber = Console.ReadLine(); //Get the Zigbee COM port from the user wirelessIn = new SerialPort(portNumber, 115200, Parity.None, 8, StopBits.One); wirelessIn.RtsEnable = true; //RTS/DTR must be enabled for communication with the ALT5801 wirelessIn.DtrEnable = false; wirelessIn.Open(); //Open the ALT5801 port //Start the recieve thread. This thread will wait for an input from the wireless module and process the input into local variables when received receiveThread = new Thread(Program.wirelessReceive); transmitThread = new Thread(Program.wirelessTransmit); //Start the GPS thread. This will read data from the GPS module and sort it into local variables until needed GPSThread = new Thread(Program.GPSupdate); receiveThread.Start(); GPSThread.Start(); /*Console.WriteLine("Enter 'COORD' for Coordinator"); * String coordDec = Console.ReadLine(); * if (String.Equals("COORD",coordDec)) * { * initALT5801(true); * } else { * initALT5801(false); * }*/ initALT5801(false); transmitThread.Start(); /*while (true) * { * String getMessage = Console.ReadLine(); * * AltCOM.genCom(wirelessIn, AltCOM.ZB_SEND_DATA(0xFFFD, 2, 0, 1, 1, Encoding.ASCII.GetBytes(getMessage))); * while (!AltGET.isMessage(rxPacket, mDef.ZB_SEND_DATA_RSP)) ; * while (!AltGET.isMessage(rxPacket, mDef.ZB_SEND_DATA_CONFIRM)) ; * Console.WriteLine("Data send Confirmed!"); * }*/ int cleanCount = 0; while (true) { bool cleanSweep = false; //Triggered true if any nodes are read active in the print loop Console.Clear(); Console.WriteLine("Active Device: "); Console.WriteLine(deviceData); Console.WriteLine(); for (int i = 0; i < devIndex; i++) { if (devRefresh[i] == true) { timeToRefresh[i] = 0; devRefresh[i] = false; } else { timeToRefresh[i]++; } if (timeToRefresh[i] < 12) { Console.WriteLine("Mesh Device {0}", i); Console.WriteLine(receivedData[i]); Console.WriteLine(); cleanSweep = true; } } //If the device was auto-configed as a coordinator, turn back into a router once a node has been found if (isCoord && cleanSweep) { Console.Clear(); transmitThread.Suspend(); initALT5801(false); transmitThread.Resume(); } if (!cleanSweep) { cleanCount++; } else { cleanCount = 0; } if (cleanCount > 40) { Console.Clear(); transmitThread.Suspend(); initALT5801(!isCoord); transmitThread.Resume(); cleanCount = 0; } Thread.Sleep(250); } }