public ThreadHandler(Threads thread) { _thread = new Thread(Work); OnJob += thread.OnJob; OnFinish += thread.OnFinish; OnAbort += thread.OnAbort; OnTerminate += thread.OnTerminate; OnException += thread.OnException; }
public Asml() { InitializeComponent(); launcher = new LauncherAdapter(); threadCamera = new Threads(); target = new TargetManager(); control = new Controller(); stopwatch = new Stopwatch(); target.AddedTarget +=manager_AddedTarget; threadCamera.DataCaptured += new EventHandler<CameraEventArgs>(thread_DataCaptured); }
public void CharacterInfoThread() { while (true) { pause.WaitOne(); Threads.UpdateTextBox(parent.txtPlayerHealth, WoW.HealthPercent.ToString()); Threads.UpdateTextBox(parent.txtPlayerPower, WoW.Power.ToString()); Threads.UpdateTextBox(parent.txtTargetHealth, WoW.TargetHealthPercent.ToString()); Threads.UpdateTextBox(parent.txtTargetCasting, WoW.TargetIsCasting.ToString()); Threads.UpdateTextBox(parent.txtRange, WoW.CountEnemyNPCsInRange.ToString()); Thread.Sleep(500); } }
public Messages CreateMessage(Threads currentThread, Users currentUser) { Console.WriteLine("Enter message:"); var inputNewMessage = Console.ReadLine(); var newMessage = new Messages(); newMessage.threadId = currentThread.threadId; newMessage.ownerId = currentUser.userId; newMessage.message = inputNewMessage; newMessage.visible = 1; return(newMessage); }
public TwitchAccount(int id, string username, string password, string token, string priority, string devicecookie, string persistent) { accountData = new AccountData(); accountData.id = id; accountData.username = username; accountData.password = password; accountData.token = token; accountData.priority = priority; accountData.devicecookie = devicecookie; accountData.persistent = persistent; threads = new Threads(); chatClient = new ChatClient(ref accountData); }
public RealTimeViewer(EventLoggerAccess log) { _log = log; IsDualEnergy = false; _realTimeViewerHost = new RealTimeViewerHost(AppConfiguration.RealTimeViewerMulticastIPAddress, AppConfiguration.RealTimeViewerDataPort, AppConfiguration.RealTimeViewerUdpClientPort, log); _inComingDataColl = new BlockingCollection <DataInfo>(); _sendThread = Threads.Create(SendAgent, ref _sendEnd, "Real Time View Data Send thread"); _sendThread.Start(); }
public string GetThreadUrl(int threadID) { BasicThread thread = Threads.GetValue(threadID); if (thread != null) { Forum forum = ForumBO.Instance.GetForum(thread.ForumID); if (forum == null) { return(string.Empty); } return(MaxLabs.bbsMax.Common.BbsUrlHelper.GetThreadUrl(forum.CodeName, threadID, thread.ThreadTypeString)); } return(string.Empty); }
public async Task SendNormalMessage(IMessageChannel channel) { var message = _user != null ? await channel.SendMessageAsync(_user.Mention + Message) : await channel.SendMessageAsync(Message); if (!_autoDelete) { return; } var threads = new Threads(); var delete = new Thread(new ParameterizedThreadStart(threads.Delete)); delete.Start(message); }
public async Task AddThread(ThreadViewModel model) { var newThread = new Threads { ForumId = model.ForumId, ThreadTitle = model.ThreadTitle, AuthorName = model.AuthorName, PostedOn = DateTime.Now, Subject = model.Subject, UserId = model.UserId }; await forumDbContext.Threads.AddAsync(newThread); await forumDbContext.SaveChangesAsync(); }
private static void Client_UpdateEvent(object sender, UpdateEventArgs e) { FB_Message msg = e.Payload as FB_Message; if (msg != null) { string fromGroup = String.Empty; if (!msg.thread_id.Equals(CurrentThreadID)) { fromGroup = $"{Threads.FirstOrDefault(t => t.uid.Equals(msg.thread_id)).name} "; } ClearCurrentLine(); Console.WriteLine($"\r{fromGroup}{PrintMSG(msg)}"); Console.Write(builder.ToString()); } }
private void ReadDataFromListen() { _listenWork = true; while (_listenWork) { try { TcpClient _tc = _tl.AcceptTcpClient(); __listen__readSmtcp reader = new __listen__readSmtcp(this, ref _tc, _protocol); lock (_tcp_Reader_Array) _tcp_Reader_Array.Add(reader); Threads.ExecAsync(reader.Start); } catch { } } }
public void LoadSingleTest() { _testint = new List<int>(); var threads = new Threads(TestingSingleThread); threads.Start(); while (threads.IsRunning()) { Threads.SleepTime(100); } for (var i = 0; i < SingleValue; i++) { Assert.That(_testint[i], Is.EqualTo(i)); } }
//----------------------------------------------------------------------------------------------- /// <summary> /// Starts the given thread /// </summary> /// <param name="thread">thread to start</param> public virtual void StartThread(GThread thread) { /// May 10, 2006 [email protected]: Fix for bug 1482578 /// Prevents the client from executing StartThread on single-use /// applications. StartThread should only be called for starting /// on-the-fly threads to multi-use applications. if (!_MultiUse) { throw new InvalidOperationException("Cannot use StartThread with single-use GApplication objects."); } Init(); Threads.Add(thread); SetThreadOnManager(thread); StartGetFinishedThreads(); }
private void SetThreadPriority(object obj) { lock (_locker) { if (SelectedThread == null) { return; } var id = SelectedThread.Id; var thread = Threads.First(info => info.Id == id); thread.Priority = SelectedThreadPriority; } }
public Thread InsertThread(string title, string content) { var currentUser = System.Threading.Thread.CurrentPrincipal.Identity.Name; var thread = new Thread { Title = title, Started = DateTime.UtcNow, StartedBy = currentUser, LastPost = DateTime.UtcNow, LastPostBy = currentUser }; Threads.Add(thread); SaveChanges(); return(thread); }
public VanillaSession(VanillaWorld world, Client player) : base(player) { this.World = world; this.Vanilla = world; OreTracker = new OreTracker(player); if (player.MinecraftUsername == null) { throw new ArgumentException("Player must be logged in, missing minecraftusername"); } thread = Threads.Create(this, RunServerReader, WatchdogKilled); thread.User = Player.MinecraftUsername; thread.Start(); }
public override async Task Run() { this.Configurations.ForEach(config => { var configTask = new Task(() => { Thread.Sleep(config.Wait); OnTriggered(config); }); Threads.Add(config, configTask); }); Threads.Values.ForEach(t => t.Start()); Task.WaitAll(Threads.Values.ToArray()); }
public void CreateLoadThreads(int num) { int numPerThread = (int)Math.Ceiling(Math.Max(((float)Worlds.Count / (float)num), 1.0f)); for (int i = 0; i < num; i++) { int min = Math.Min((numPerThread) * i, Worlds.Count); int max = Math.Min(min + numPerThread, Worlds.Count); if (max - min > 0) { Thread loadThread = new Thread(() => WorldLoaderThread(min, max)); loadThread.Start(); Threads.Add(loadThread); } } }
private void GetThreadsFromDocument(XmlNode document) { XmlNode element = document.FirstChild; if (element == null || element.Name != "root") { throw new XmlException(); } foreach (XmlElement childElement in element.ChildNodes) { Thread thread = Thread.GetThreadFromElement(childElement); Threads.Add(thread); } IsSave = true; }
private void StartThreads() { foreach (var car in Cars) { Thread carThread = new Thread(new ParameterizedThreadStart(Ride)) { Name = car.Name }; Threads.Add(carThread); } for (int i = 0; i < Threads.Count; i++) { Threads[i].Start(Cars[i]); Cars[i].Time.Start(); } }
private async void SaveButton_Clicked(object sender, EventArgs e) { SaveButton.IsEnabled = false; ToolbarItem button = sender as ToolbarItem; bool issaved = false; if (Threads.IsSaved(thread)) { issaved = !(await Threads.RemoveSavedThread(thread)); } else { issaved = await Threads.SaveNewThread(thread); } SaveButton.Text = issaved ? Strings.Unsave : Strings.Save; SaveButton.IsEnabled = true; }
private void SearchTextChanged() { Predicate <ThreadViewModel> filter = (ThreadViewModel tvm) => { if (tvm.InitialPost == null) { return(false); } return(tvm.InitialPost.SimpleComment.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) >= 0 || (tvm.InitialPost.Subject != null && tvm.InitialPost.Subject.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) >= 0)); }; Threads.ApplyFilter(filter); ImageThreads.ApplyFilter(filter); Watchlist.ApplyFilter(filter); }
public void populatePosts() { var posts = new List <Post>(); foreach (var i in Enumerable.Range(30, 140)) { var test = Threads.ToList().Random(); var user = GetRandomUser(); AddToPostCountOfUser(user.Username); posts.Add(new Post { author = user, post = LoremNET.Lorem.Paragraph(4, 20, 3, 10), thread = test }); } Posts.AddRange(posts); SaveChanges(); }
private static void OnActorResize(object sender, AllocationChangedArgs args) { Actor actor = (Actor)sender; if (idleResizeId == 0) { idleResizeId = Threads.AddTimeoutFull(50, 1000, delegate { float width, height; actor.GetSize(out width, out height); ((Canvas)actor.Content).SetSize((int)Math.Ceiling(width), (int)Math.Ceiling(height)); idleResizeId = 0; return(false); }); } }
// ********************************************************************* // InitializePostListControlTemplate // /// <summary> /// Render the post list view /// </summary> /// // ********************************************************************/ private void InitializePostListControlTemplate() { // Initialize common display elements InitializeCommonTemplateItems(); // Find the postList control postList = (PostList)controlTemplate.FindControl("PostList"); // Ascending or descending sortOrder = (DropDownList)controlTemplate.FindControl("SortOrder"); if (sortOrder != null) { if (user != null) { sortOrder.Items.FindByValue(Convert.ToInt32(user.ShowPostsAscending).ToString()).Selected = true; } sortOrder.AutoPostBack = true; sortOrder.SelectedIndexChanged += new System.EventHandler(SortOrder_Changed); } // Find the pager pager = (Paging)controlTemplate.FindControl("Pager"); pager.PageIndex_Changed += new System.EventHandler(PageIndex_Changed); // Get the total records used in the pager pager.TotalRecords = Threads.GetTotalPostsForThread(PostID); // Set up the email tracking check changed event postList.ThreadTracking_Changed += new System.EventHandler(Toggle_ThreadTracking); // Set the datasource // If we're in a post back someone else probably wants to render the view // Set the datasource if (user != null) { postList.DataSource = Posts.GetThreadByPostID(PostID, pager.PageIndex, pager.PageSize, 0, Convert.ToInt32(user.ShowPostsAscending)); Posts.MarkPostAsRead(PostID, user.Username); } else { postList.DataSource = Posts.GetThreadByPostID(PostID, pager.PageIndex, pager.PageSize, 0, Convert.ToInt32(sortOrder.SelectedItem.Value)); } postList.DataBind(); }
/// <summary> /// 停止循环工作。 /// 只能停止循环而已,如果已经有一批任务在处理, /// 则内部需要捕获ThreadAbortException异常,否则无法停止任务处理。 /// </summary> public virtual void StopWork() { NeedStopProcess = true; WriteLine("正在停止服务..."); //停止服务管理线程 StopManagerThread(); //if (threads != null && threads.IsAlive) threads.Abort(); if (Threads != null) { WriteLine("正在等待现有线程执行完毕..."); DateTime waitStart = DateTime.Now; while (waitStart.AddMinutes(10d) < DateTime.Now) { if (Threads.FindAll(t => t.IsAlive).Count() > 0) { //有执行中的线程,就继续等待,最多等待10分钟 Thread.Sleep(100); } else { WriteLine("等待超时,强行终止所有线程"); break; } } foreach (var item in Threads) { try { if (item != null && item.IsAlive) { item.Abort(); } } catch (Exception ex) { WriteLine(ex.ToString()); } } } WriteLine("服务已停止"); //Interactive.Hide(); }
protected override void WndProc(ref Message m) { try { if (m.Msg == 0x02B1) { int sessionid = (int)m.LParam; WM_WTSSESSION_CHANGE para2 = (WM_WTSSESSION_CHANGE)m.WParam; Threads.ExecAsync(() => { rdc.onSessionChanged(sessionid, para2); }); } } catch { } base.WndProc(ref m); }
public int CalculateAverage(Threads model, int value1 = 0, int value2 = 0, int value3 = 0) { if (model.FirstValue != 0 || model.SecondValue != 0 || model.ThirdValue != 0) { return model.Average = model.FirstValue + model.SecondValue + model.ThirdValue / 3; } else { Random rand = new Random(); value1 = rand.Next(1, 101); value2 = rand.Next(1, 101); value3 = rand.Next(1, 101); return model.Average = value1 + value2 + value3 / 3; } }
private void Window_Loaded(object sender, RoutedEventArgs e) { for (int i = 0; i < 80; i++) { gameGrid.ColumnDefinitions.Add(new ColumnDefinition()); gameGrid.RowDefinitions.Add(new RowDefinition()); } //Grid.SetColumn(datum, 0); //Grid.SetRow(datum, gameGrid.RowDefinitions.Count - 2); //Grid.SetColumnSpan(datum, gameGrid.ColumnDefinitions.Count); //Grid.SetColumn(output, 0); //Grid.SetRow(output, gameGrid.RowDefinitions.Count - 1); //Grid.SetColumnSpan(output, gameGrid.ColumnDefinitions.Count); control = new int[gameGrid.ColumnDefinitions.Count, gameGrid.RowDefinitions.Count - 2]; Threads.AddThread("LoadAll", new System.Threading.Thread(new System.Threading.ThreadStart(() => this.business.LoadAll())), true); this.business.LoadAllFinished += Business_LoadAllFinished; }
/// <summary> /// Remove a ThreadStarter element from the internal thread list /// </summary> /// <remarks> /// Raises the <see cref="ThreadRemoved" /> event. /// </remarks> /// <param name="thread">The ThreadStarter element to remove</param> private static void UnregisterThread(ThreadStarter thread) { try { Threads.Remove(thread); } catch (ArgumentOutOfRangeException e) { TraceHelper.TraceError(string.Format("ThreadStarter.UnregisterThread encountered an exception: {0}", e.Message)); } finally { if (ThreadRemoved != null) { ThreadRemoved(null, thread); } } }
public void populateThreads() { var threads = new List <Thread>(); var rnd = new Random(); foreach (var i in Enumerable.Range(0, 40)) { var test = Sections.ToList().Random(); var user = GetRandomUser(); AddToPostCountOfUser(user.Username); threads.Add(new Thread { author = user, name = Lorem.Words(2, 5), post = LoremNET.Lorem.Paragraph(4, 20, 3, 10), section = test }); } Threads.AddRange(threads); SaveChanges(); }
public static void ReplyToThread(string message, int threadId, string image, string author = "Аноним") { using (ApplicationContext db = new ApplicationContext()) { Posts post = new Posts() { Message = message, ThreadId = threadId, Image = image, Author = author, Time = DateTime.Now }; Threads thread = db.Threads.Where(x => x.Id == threadId).FirstOrDefault(); thread.lastBump = DateTime.Now; db.Posts.Add(post); db.SaveChanges(); } }
public ElaUnit Wait(int timeout, ElaAsync obj) { var th = obj.Thread; if (th != null) { if (th.Join(timeout)) { lock (syncRoot) { Threads.Remove(th); obj.Thread = null; } } } return(ElaUnit.Instance); }
public void TestUpdate_Service() { for (int i = 0; i < 5; i++) { DiscoveryConfig discoveryConfig = Constants.NewDiscoveryConfig(); string serviceId = discoveryConfig.ServiceId; DefaultServiceChangeListener listener = new DefaultServiceChangeListener(); _serviceRepository.RegisterServiceChangeListener(discoveryConfig, listener); Assert.IsTrue(_serviceRepository.ContainsService(serviceId)); Service service1 = new Service() { ServiceId = serviceId, Instances = new List <Instance>() { Constants.NewInstance(serviceId) } }; Service service2 = new Service() { ServiceId = serviceId, Instances = new List <Instance>() { Constants.NewInstance(serviceId), Constants.NewInstance(serviceId) } }; _serviceRepository.Update(service1); _serviceRepository.Update(service2); _serviceRepository.Update(new Service() { ServiceId = serviceId + "1" }); Threads.Sleep(100); Assert.AreEqual(2, listener.ServiceChangeEvents.Count); foreach (ServiceChangeEvent e in listener.ServiceChangeEvents) { Assert.AreEqual(InstanceChange.CHANGE_TYPE.RELOAD, e.ChangeType); } } }
public int CalculateMin(Threads model, int value1 = 0, int value2 = 0, int value3 = 0) { if (model.FirstValue != 0 || model.SecondValue != 0 || model.ThirdValue != 0) { if (model.FirstValue < model.SecondValue && model.FirstValue < model.ThirdValue) { return model.FirstValue; } else if (model.SecondValue < model.FirstValue && model.SecondValue < model.ThirdValue) { return model.SecondValue; } else { return model.ThirdValue; } } else { Random rand = new Random(); value1 = rand.Next(1, 101); value2 = rand.Next(1, 101); value3 = rand.Next(1, 101); if (value1 < value2 && value1 < value3) { return value1; } else if (value2 < value1 && value2 < value3) { return value2; } else { return value3; } } }
public void DoesThreadsDoWhatTheyHaveToDo() { _testint = new List<int>(); const int value = 1000000; var threads = new Threads(value, TestingThreads); threads.Start(); while(threads.IsRunning()) { Threads.SleepTime(500); } _testint.Sort(); for (var i = 0; i < value; i++) { Assert.That(_testint[i], Is.EqualTo(i)); } }
public static void testTimer(int threadSelected) { Threads model = new Threads(); CalculateValues calculate = new CalculateValues(); int minValue = 0; int maxValue = 0; int avgValue = 0; if (threadSelected == 1) { Thread minThread = new Thread(() => minValue = calculate.CalculateMin(model)); minThread.Start(); minThread.Join(); model.Min = minValue; model.Task = "Minimum"; model.LastExecution = DateTime.UtcNow; AddValuesToSQL add = new AddValuesToSQL(); SaveATaskList addTask = new SaveATaskList(); addTask.SaveTaskList(model); add.SaveData(model); } else if (threadSelected == 2) { Thread maxThread = new Thread(() => maxValue = calculate.CalculateMax(model)); maxThread.Start(); maxThread.Join(); model.Max = maxValue; model.Task = "Maximum"; model.LastExecution = DateTime.UtcNow; AddValuesToSQL add = new AddValuesToSQL(); SaveATaskList addTask = new SaveATaskList(); addTask.SaveTaskList(model); add.SaveData(model); } else { Thread avgThread = new Thread(() => avgValue = calculate.CalculateAverage(model)); avgThread.Start(); avgThread.Join(); model.Average = avgValue; model.Task = "Average"; model.LastExecution = DateTime.UtcNow; AddValuesToSQL add = new AddValuesToSQL(); SaveATaskList addTask = new SaveATaskList(); addTask.SaveTaskList(model); add.SaveData(model); } }
/// <summary> /// Creates a threaded rating for the given rating forum /// </summary> /// <param name="RatingForum">The forum to post to</param> /// <param name="rating">The rating to add</param> /// <returns>The created rating object</returns> public ThreadInfo RatingThreadCreate(RatingForum ratingForum, RatingInfo rating) { ISite site = SiteList.GetSite(ratingForum.SiteName); //check for repeat posting ValidateRating(ratingForum, rating, site); Threads threadsObj = new Threads(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList); threadsObj.CallingUser = CallingUser; threadsObj.BbcUid = BbcUid; threadsObj.IpAddress = IpAddress; //create the thread entry ThreadInfo createdThread = threadsObj.ThreadCreate((Forum)ratingForum, (RatingInfo)rating); using (var reader = CreateReader("ratingscreate")) { reader.AddParameter("entryid", createdThread.rating.ID); reader.AddParameter("uid", ratingForum.Id); reader.AddParameter("rating", rating.rating); reader.AddParameter("userid", CallingUser.UserID); reader.AddParameter("siteid", site.SiteID); reader.Execute(); } createdThread.rating.rating = rating.rating; return createdThread; }
public Threads MinMaxAvgThread(Threads model) { CalculateValues calculate = new CalculateValues(); int minValue = 0; int maxValue = 0; int avgValue = 0; Thread minThread = new Thread(() => minValue = calculate.CalculateMin(model)); Thread maxThread = new Thread(() => maxValue = calculate.CalculateMax(model)); Thread avgThread = new Thread(() => avgValue = calculate.CalculateAverage(model)); string name = "TestThread"; minThread.Start(); maxThread.Start(); avgThread.Start(); minThread.Join(); maxThread.Join(); avgThread.Join(); model.Min = minValue; model.Max = maxValue; model.Average = avgValue; model.Task = name; model.LastExecution = DateTime.UtcNow; if (!minThread.IsAlive && !maxThread.IsAlive && !avgThread.IsAlive) { AddValuesToSQL add = new AddValuesToSQL(); SaveATaskList addTask = new SaveATaskList(); addTask.SaveTaskList(model); add.SaveData(model); } return model; }
/// <summary> /// Returns the Threads in a rating forum by the UID /// </summary> /// <param name="reviewForumId"></param> /// <param name="site"></param> /// <returns></returns> public ThreadList RatingForumThreadsReadByUID(string reviewForumId, ISite site) { Threads threadsObj = new Threads(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList); threadsObj.CallingUser = CallingUser; threadsObj.BbcUid = BbcUid; threadsObj.IpAddress = IpAddress; return threadsObj.ThreadsReadByUid(reviewForumId, site); }
/// <summary> /// Returns the Comments of a Thread in a rating forum by the threadid /// </summary> /// <param name="threadID"></param> /// <param name="site"></param> /// <returns>List of Comments</returns> public CommentsList RatingForumThreadCommentReadByID(string threadID, ISite site) { Threads threadsObj = new Threads(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList); threadsObj.CallingUser = CallingUser; threadsObj.BbcUid = BbcUid; threadsObj.IpAddress = IpAddress; int id = 0; Int32.TryParse(threadID, out id); return threadsObj.ThreadCommentsReadById(id, site); }
public Stream GetReviewForumThreads(string reviewForumId, string siteName) { ThreadList ratingForumThreadData = null; Stream output = null; if (_ratingObj.FilterBy == FilterBy.UserList) { //return GetReviewForumThreadsByUserList(reviewForumId, siteName, QueryStringHelper.GetQueryParameterAsString("userList", "")); } try { ISite site = GetSite(siteName); Threads _threadsObj = new Threads(dnaDiagnostic, readerCreator, cacheManager, siteList); ratingForumThreadData = _ratingObj.RatingForumThreadsReadByUID(reviewForumId, site); //if null then send back 404 if (ratingForumThreadData == null) { throw new DnaWebProtocolException(System.Net.HttpStatusCode.NotFound, string.Format("Review forum '{0}' does not exist for site '{1}'", reviewForumId, siteName), null); } else { output = GetOutputStream(ratingForumThreadData, ratingForumThreadData.LastUpdate); } } catch (DnaException ex) { throw new DnaWebProtocolException(System.Net.HttpStatusCode.InternalServerError, ex.Message, ex); } return output; }
} // ctor public static void Main( String[] args ) { Threads worker; if ( args.Length > 0 ) { int threads = 250; bool exception = true; // command-line options: // -t<number> -- number of threads (default is 250) // -n -- no exception thread (default is true) for ( int i = 0; i < args.Length; i++ ) { if ( args[i].Length >= 2 && args[i][0] == '-' ) { switch ( args[i][1] ) { case 't': threads = Int32.Parse( args[i].Substring( 2, args[i].Length - 2 ), CultureInfo.InvariantCulture ); break; case 'n': exception = false; break; default: throw new Exception( "Invalid Command-Line Arguments" ); } } else throw new Exception( "Invalid Command-Line Arguments" ); } worker = new Threads( threads, exception ); } else worker = new Threads(); worker.DoWork(); } // main