public ModbusServer(string IP, int Port) { m_ModbusServerData = new ModbusServerData(); m_SyncEvents = new SyncEvents(); m_Server = new ModbusServerThread(m_SyncEvents, IP, Port, m_ModbusServerData); m_ServerThread = new Thread(m_Server.ThreadRun); }
static void Main() { Queue <int> queue = new Queue <int>(); SyncEvents syncEvents = new SyncEvents(); Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); producerThread.Join(); consumerThread.Join(); Console.ReadKey(); }
public void AddSyncEvent(string entityName, int entityId) { SyncEvents.Add(new SyncEvent { TenantId = TenantId, EntityName = entityName, EntityId = entityId, ModifiedOn = DateTime.UtcNow }); // trim sync events SyncEvents.RemoveAll(item => item.ModifiedOn < DateTime.UtcNow.AddHours(-1)); }
public ModbusServerThread(SyncEvents e, string IP, int Port, ModbusServerData IO) { m_SyncEvents = e; m_IP = IP; m_Port = Port; m_LastState = State.Unknown; m_NextState = m_LastState; m_ModbusServerData = IO; }
public DataConsumerDelegate(outputDelegate dd, bool tight) { mySyncEvent = new SyncEvents(); myQueue = new Queue <RawData>(); myThread = new Thread(this.ThreadRun); _tight = tight; _queue = myQueue; _syncEvents = mySyncEvent; _outputDeletgate = dd; }
public Form1() { try { initTime = DateTime.Now; //Calls calculation method for filters highCoeff = filterCoeff(double.Parse(ConfigurationManager.AppSettings.Get("angleHighPass")), sampFreq / bufferSize, "High"); lowCoeff = filterCoeff(double.Parse(ConfigurationManager.AppSettings.Get("angleLowPass")), sampFreq / bufferSize, "Low"); bandHighCoeff = filterCoeff(double.Parse(ConfigurationManager.AppSettings.Get("velocityHighPass")), sampFreq / bufferSize, "High"); bandLowCoeff = filterCoeff(double.Parse(ConfigurationManager.AppSettings.Get("velocityLowPass")), sampFreq / bufferSize, "Low"); //2*10^-2 InitializeComponent(); // Initializes the visual components SetSize(); // Sets up the size of the window and the corresponding location of the components Frameco = 0; dayFrameCo0 = DayNr.GetDayNr(DateTime.Now); //Initialization of TwinCAT connection. 851 is the port for PLC runtime 1 if (twinCatBool) { tcAds.Connect(851); } myStopwatch = new Stopwatch(); dataWritingSyncEvent = new SyncEvents(); consumerd = new DataConsumerDelegate[2]; consumerd[0] = new DataConsumerDelegate(new DataConsumerDelegate.outputDelegate(showStatistics), true); consumerd[1] = new DataConsumerDelegate(new DataConsumerDelegate.outputDelegate(Pattern), true); consumerd[1].myThread.Priority = ThreadPriority.Highest; for (int i = 0; i < consumerd.Length; i++) { consumerd[i].myThread.Start(); } dataWritingQueue = new Queue <PeakQueueItem>(); dataWritingThreadBool = true; dataWritingThread = new Thread(dataWrite); dataWritingThread.Priority = ThreadPriority.Highest; dataWritingThread.Start(); Thread.Sleep(10); cameraThread = new Thread(initCamera); cameraThread.Priority = ThreadPriority.Highest; cameraThread.Start(); curDirec = System.IO.Path.GetDirectoryName(Application.ExecutablePath); System.Diagnostics.Process.Start(curDirec + "\\AffinitySet.bat"); } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { EmailError.emailAlert(ex); throw (ex); } }
//clear the current list of items and load the new items through GetItemsAsync //this is executed when the user refreshes the list async Task ExecuteLoadItemsCommand() { //the code will run only when IsBusy is false if (IsBusy) { return; } //make is busy ture so that the user can't run this twice while it is runnig IsBusy = true; Debug.WriteLine("[ExecuteLoadItemsCommand]Start loading items..."); try { //clear all the items in the list Items.Clear(); ItemGrouped.Clear(); Debug.WriteLine("[ExecuteLoadItemsCommand]Cleared items list"); //update the list only if it is connected to the internet if (CrossConnectivity.Current.IsConnected) { //get new events online, and add them to the database if there is a new one await SyncEvents.UpdateAcaEventsAsync(); } else { Debug.WriteLine("No internet connection"); } var itemsInDb = await App.Database.SortListByDate(); //add all the items to the list foreach (var item in itemsInDb) { //add items to the list Items.Add(item); } //refresh the grouped item list SetupGroup(Items); } catch (Exception ex) { await SyncEvents.SendErrorEmail(ex.Message); } finally { //set the IsBusy to false after the program finishes IsBusy = false; ScrollToEvent = true; Debug.WriteLine("[ExecuteLoadItemsCommand]There are " + Items.Count + " items in the database"); } }
public SaveAsynchronous(ConsumeDelegate consumeMethod, string threadName, ThreadPriority threadPriority, bool autoStart) { if (consumeMethod == null) throw new ArgumentNullException("consumeMethod"); _consumeMethod = consumeMethod; _queue = Queue.Synchronized(new Queue()); _syncEvents = new SyncEvents(); _threadPriority = threadPriority; _threadName = threadName; ExecutionTime(); if (autoStart) Start(); }
static void Main() { // Настройка структуры, содержащей сведения о событии, необходимые // для синхронизации потоков. SyncEvents syncEvents = new SyncEvents(); // Коллекция универсальной очереди применяется для хранения элементов, // предназначенных для создания и использования. В этом случае используется тип 'int'. Queue <int> queue = new Queue <int>(); // Формирование объектов: одного -- для создания элементов, а другого -- для // их использования. Очередь и события синхронизации // потоков передаются обоим объектам. Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); // Создание потоковых объектов для объектов источника // и приемника. Это не приводит к созданию или запуску // реальных потоков. Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); // Создание и запуск обоих потоков. Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); // Настройка потоков источника и приемника на работу в течение 10 секунд. // Использование главного потока (потока, выполняющего данный метод) // для отображения содержимого очереди каждые 2,5 секунды. for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } // Передача обоим потокам -- и источника, и приемника -- сигнала о необходимости завершить работу. // Ответят оба потока, поскольку ExitThreadEvent -- это // событие, сбрасываемое вручную, поэтому оно остается в состоянии 'set', пока не будет сброшено явным образом. Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); // Применение метода Join для блокирования главного потока; сначала -- до момента завершения работы // потока источника, а затем -- до завершения работы потока приемника. Console.WriteLine("main thread waiting for threads to finish..."); producerThread.Join(); consumerThread.Join(); }
static void Main() { // Configure struct containing event information required // for thread synchronization. SyncEvents syncEvents = new SyncEvents(); // Generic Queue collection is used to store items to be // produced and consumed. In this case 'int' is used. Queue <int> queue = new Queue <int>(); // Create objects, one to produce items, and one to // consume. The queue and the thread synchronization // events are passed to both objects. Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); // Create the thread objects for producer and consumer // objects. This step does not create or launch the // actual threads. Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); // Create and launch both threads. Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); // Let producer and consumer threads run for 10 seconds. // Use the primary thread (the thread executing this method) // to display the queue contents every 2.5 seconds. for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } // Signal both consumer and producer thread to terminate. // Both threads will respond because ExitThreadEvent is a // manual-reset event--so it stays 'set' unless explicitly reset. Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); // Use Join to block primary thread, first until the producer thread // terminates, then until the consumer thread terminates. Console.WriteLine("main thread waiting for threads to finish..."); producerThread.Join(); consumerThread.Join(); }
static void Main() { // 配置结构,该结构包含线程同步 // 所需的事件信息。 SyncEvents syncEvents = new SyncEvents(); // 泛型队列集合用于存储要制造和使用的 // 项。此例中使用的是“int”。 Queue <int> queue = new Queue <int>(); // 创建对象,一个用于制造项,一个用于 // 使用项。将队列和线程同步事件传递给 // 这两个对象。 Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); // 为制造者对象和使用者对象创建线程 // 对象。此步骤并不创建或启动 // 实际线程。 Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); // 创建和启动两个线程。 Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); // 为制造者线程和使用者线程设置 10 秒的运行时间。 // 使用主线程(执行此方法的线程) // 每隔 2.5 秒显示一次队列内容。 for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } // 向使用者线程和制造者线程发出终止信号。 // 这两个线程都会响应,由于 ExitThreadEvent 是 // 手动重置的事件,因此除非显式重置,否则将保持“设置”。 Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); // 使用 Join 阻塞主线程,首先阻塞到制造者线程 // 终止,然后阻塞到使用者线程终止。 Console.WriteLine("main thread waiting for threads to finish..."); producerThread.Join(); consumerThread.Join(); }
/* * //execute when the AddItem button is touched * async void AddItem_Clicked(object sender, EventArgs e) * { * //show a new page called NewItemPage * await Navigation.PushModalAsync(new NavigationPage(new NewItemPage())); * * } */ async void ExportItem_Clicked(object sender, EventArgs e) { var answer = DisplayAlert("Export events", "Do you wish to export all the academic events to your device calendar?", "Yes", "No"); if (await answer) { try { //execute export events await SyncEvents.ExportEvents(); } catch (Exception ex) { await SyncEvents.SendErrorEmail(ex.Message); } } }
private static void ProducerConsumerThreadStart() { Queue <byte[]> queue = new Queue <byte[]>(); SyncEvents sync = new SyncEvents(); Producer producer = new Producer(queue, sync); Thread producerThread = new Thread(producer.ThreadRun); producerThread.Start(); for (int i = 0; i < Environment.ProcessorCount; i++) { Consumer consumer = new Consumer(queue, sync); Thread consumerThread = new Thread(consumer.ThreadRun); sync.tPool.Add(consumerThread); consumerThread.Start(); } }
static void Main() { Queue <int> queue = new Queue <int>(); SyncEvents syncEvents = new SyncEvents(); Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread1 = new Thread(consumer.ThreadRun); Thread consumerThread2 = new Thread(consumer.ThreadRun); Thread consumerThread3 = new Thread(consumer.ThreadRun); Thread consumerThread4 = new Thread(consumer.ThreadRun); Console.WriteLine("Launching producer and consumers threads..."); Stopwatch sw = new Stopwatch(); sw.Start(); producerThread.Start(); consumerThread1.Start(); consumerThread2.Start(); consumerThread3.Start(); consumerThread4.Start(); // for (int i=0; i<4; i++) // { // Thread.Sleep(2500); // ShowQueueContents(queue); // } // // Console.WriteLine("Signaling threads to terminate..."); // syncEvents.ExitThreadEvent.Set(); producerThread.Join(); consumerThread1.Join(); consumerThread2.Join(); consumerThread3.Join(); consumerThread4.Join(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds + "ms"); }
public DataConsumerDelegate(Queue <RawData> q, SyncEvents e, outputDelegate dd) { _queue = q; _syncEvents = e; _outputDeletgate = dd; }
static void Main() { // Configure struct containing event information required // for thread synchronization. SyncEvents syncEvents = new SyncEvents(); // Generic Queue collection is used to store items to be // produced and consumed. In this case 'int' is used. Queue<int> queue = new Queue<int>(); // Create objects, one to produce items, and one to // consume. The queue and the thread synchronization // events are passed to both objects. Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); // Create the thread objects for producer and consumer // objects. This step does not create or launch the // actual threads. Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); // Create and launch both threads. Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); // Let producer and consumer threads run for 10 seconds. // Use the primary thread (the thread executing this method) // to display the queue contents every 2.5 seconds. for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } // Signal both consumer and producer thread to terminate. // Both threads will respond because ExitThreadEvent is a // manual-reset event--so it stays 'set' unless explicitly reset. Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); // Use Join to block primary thread, first until the producer thread // terminates, then until the consumer thread terminates. Console.WriteLine("main thread waiting for threads to finish..."); producerThread.Join(); consumerThread.Join(); }
public Producer(Queue<int> q, SyncEvents e) { _queue = q; _syncEvents = e; }
public Consumer(Queue<int> q, SyncEvents e) { _queue = q; _syncEvents = e; }
static void Main() { Queue<int> queue = new Queue<int>(); SyncEvents syncEvents = new SyncEvents(); Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); producerThread.Join(); consumerThread.Join(); Console.ReadKey(); }
static void Main() { // 配置结构,该结构包含线程同步 // 所需的事件信息。 SyncEvents syncEvents = new SyncEvents(); // 泛型队列集合用于存储要制造和使用的 // 项。此例中使用的是“int”。 Queue<int> queue = new Queue<int>(); // 创建对象,一个用于制造项,一个用于 // 使用项。将队列和线程同步事件传递给 // 这两个对象。 Console.WriteLine("Configuring worker threads..."); Producer producer = new Producer(queue, syncEvents); Consumer consumer = new Consumer(queue, syncEvents); // 为制造者对象和使用者对象创建线程 // 对象。此步骤并不创建或启动 // 实际线程。 Thread producerThread = new Thread(producer.ThreadRun); Thread consumerThread = new Thread(consumer.ThreadRun); // 创建和启动两个线程。 Console.WriteLine("Launching producer and consumer threads..."); producerThread.Start(); consumerThread.Start(); // 为制造者线程和使用者线程设置 10 秒的运行时间。 // 使用主线程(执行此方法的线程) // 每隔 2.5 秒显示一次队列内容。 for (int i = 0; i < 4; i++) { Thread.Sleep(2500); ShowQueueContents(queue); } // 向使用者线程和制造者线程发出终止信号。 // 这两个线程都会响应,由于 ExitThreadEvent 是 // 手动重置的事件,因此除非显式重置,否则将保持“设置”。 Console.WriteLine("Signaling threads to terminate..."); syncEvents.ExitThreadEvent.Set(); // 使用 Join 阻塞主线程,首先阻塞到制造者线程 // 终止,然后阻塞到使用者线程终止。 Console.WriteLine("main thread waiting for threads to finish..."); producerThread.Join(); consumerThread.Join(); }
public Consumer(Queue <int> q, SyncEvents e) { _queue = q; _syncEvents = e; }
public Producer(Queue <int> q, SyncEvents e) { _queue = q; _syncEvents = e; }
public List <SyncEvent> GetSyncEvents(DateTime lastSyncDate) { return(SyncEvents.Where(item => item.TenantId == TenantId && item.ModifiedOn >= lastSyncDate).ToList()); }
public WebUpdateConsumer(Queue <WebDefinitionHelper> q, SyncEvents e) { _queue = q; _syncEvents = e; }