• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Thread类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Thread的典型用法代码示例。如果您正苦于以下问题:C# Thread类的具体用法?C# Thread怎么用?C# Thread使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Thread类属于命名空间,在下文中一共展示了Thread类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: TransportJobPrice

 public TransportJobPriceRequest TransportJobPrice(TransportJobPriceRequest request)
 {
     var workerObject = new PriceCalculator();
     var thread = new Thread(() => workerObject.PriceCalc(request));
     thread.Start();
     return new TransportJobPriceRequest();
 }
开发者ID:MarioQueiros,项目名称:RememberVinilWebStore,代码行数:7,代码来源:TransportadoraService.cs


示例2: handleMessage

        // DeckList && LibraryView
        public void handleMessage(Message msg)
        {
            if( msg is LibraryViewMessage && config.ContainsKey("user-id") ) {
                LibraryViewMessage viewMsg = (LibraryViewMessage) msg;
                if( !viewMsg.profileId.Equals(App.MyProfile.ProfileInfo.id) ) {
                    return;
                }

                inventoryCards.Clear();
                foreach( Card card in viewMsg.cards ) {
                    inventoryCards[card.id] = String.Format("{0},{1}", card.typeId, card.tradable ? 1 : 0);
                }

                if( dataPusher == null ) {
                    if( config.ContainsKey("last-card-sync") ) {
                        dataPusher = new Thread(new ThreadStart(DelayedPush));
                    } else {
                        dataPusher = new Thread(new ThreadStart(Push));
                    }

                    dataPusher.Start();
                }

            //} else if( msg is DeckCardsMessage ) {
            //    DeckCardsMessage deckMsg = (DeckCardsMessage)msg;
            //} else if( msg is DeckSaveMessage ) {
            }
        }
开发者ID:noHero123,项目名称:ScrollsPost,代码行数:29,代码来源:CollectionSync.cs


示例3: SerialPortHandler

 public SerialPortHandler(string p)
 {
     this.SPH_Thread = new Thread(new ThreadStart(this.Read));
     this.SPH_Running = true;
     this.port = p;
     this.verbose_mode = 0;
 }
开发者ID:42burritos,项目名称:PFC_CORE,代码行数:7,代码来源:SerialPortHandler.cs


示例4: StackFrame

		internal StackFrame(Thread thread, ICorDebugILFrame corILFrame, uint chainIndex, uint frameIndex)
		{
			this.process = thread.Process;
			this.thread = thread;
			this.appDomain = process.AppDomains[corILFrame.GetFunction().GetClass().GetModule().GetAssembly().GetAppDomain()];
			this.corILFrame = corILFrame;
			this.corILFramePauseSession = process.PauseSession;
			this.corFunction = corILFrame.GetFunction();
			this.chainIndex = chainIndex;
			this.frameIndex = frameIndex;
			
			MetaDataImport metaData = thread.Process.Modules[corFunction.GetClass().GetModule()].MetaData;
			int methodGenArgs = metaData.EnumGenericParams(corFunction.GetToken()).Length;
			// Class parameters are first, then the method ones
			List<ICorDebugType> corGenArgs = ((ICorDebugILFrame2)corILFrame).EnumerateTypeParameters().ToList();
			// Remove method parametrs at the end
			corGenArgs.RemoveRange(corGenArgs.Count - methodGenArgs, methodGenArgs);
			List<DebugType> genArgs = new List<DebugType>(corGenArgs.Count);
			foreach(ICorDebugType corGenArg in corGenArgs) {
				genArgs.Add(DebugType.CreateFromCorType(this.AppDomain, corGenArg));
			}
			
			DebugType debugType = DebugType.CreateFromCorClass(
				this.AppDomain,
				null,
				corFunction.GetClass(),
				genArgs.ToArray()
			);
			this.methodInfo = (DebugMethodInfo)debugType.GetMember(corFunction.GetToken());
		}
开发者ID:Bombadil77,项目名称:SharpDevelop,代码行数:30,代码来源:StackFrame.cs


示例5: Start

 public void Start()
 {
     try
     {
         //Starting the TCP Listener thread.
         sampleTcpThread = new Thread(new ThreadStart(StartListen2));
         sampleTcpThread.Start();
         Console.Message = ("Started SampleTcpUdpServer's TCP Listener Thread!\n"); OnChanged(EventArgs.Empty);
     }
     catch (Exception e)
     {
         Console.Message = ("An TCP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
         sampleTcpThread.Abort();
     }
     try
     {
         //Starting the UDP Server thread.
         sampleUdpThread = new Thread(new ThreadStart(StartReceiveFrom2));
                 sampleUdpThread.Start();
         Console.Message = ("Started SampleTcpUdpServer's UDP Receiver Thread!\n"); OnChanged(EventArgs.Empty);
     }
     catch (Exception e)
     {
         Console.Message = ("An UDP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
         sampleUdpThread.Abort();
     }
 }
开发者ID:profimedica,项目名称:SYKYO,代码行数:27,代码来源:UdpServer.cs


示例6: StartListening

        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
开发者ID:Riketta,项目名称:rust-anticheat,代码行数:35,代码来源:Server.cs


示例7: LoadingScreen

		/// <summary>
		/// The constructor is private: loading screens should
		/// be activated via the static Load method instead.
		/// </summary>
		private LoadingScreen (ScreenManager screenManager,bool loadingIsSlow, 
				GameScreen[] screensToLoad)
			{
			this.loadingIsSlow = loadingIsSlow;
			this.screensToLoad = screensToLoad;

			TransitionOnTime = TimeSpan.FromSeconds (0.5);

			// If this is going to be a slow load operation, create a background
			// thread that will update the network session and draw the load screen
			// animation while the load is taking place.
			if (loadingIsSlow) {
				backgroundThread = new Thread (BackgroundWorkerThread);
				backgroundThreadExit = new ManualResetEvent (false);

				graphicsDevice = screenManager.GraphicsDevice;

				// Look up some services that will be used by the background thread.
				IServiceProvider services = screenManager.Game.Services;

				networkSession = (NetworkSession)services.GetService (
							typeof(NetworkSession));

				messageDisplay = (IMessageDisplay)services.GetService (
							typeof(IMessageDisplay));
			}
		}
开发者ID:Nailz,项目名称:MonoGame-Samples,代码行数:31,代码来源:LoadingScreen.cs


示例8: AnalysisQueue

            internal AnalysisQueue(VsProjectAnalyzer analyzer) {
                _workEvent = new AutoResetEvent(false);
                _cancel = new CancellationTokenSource();
                _analyzer = analyzer;

                // save the analysis once it's ready, but give us a little time to be
                // initialized and start processing stuff...
                _lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);

                _queue = new List<IAnalyzable>[PriorityCount];
                for (int i = 0; i < PriorityCount; i++) {
                    _queue[i] = new List<IAnalyzable>();
                }
                _enqueuedGroups = new HashSet<IGroupableAnalysisProject>();

                _workThread = new Thread(Worker);
                _workThread.Name = "Node.js Analysis Queue";
                _workThread.Priority = ThreadPriority.BelowNormal;
                _workThread.IsBackground = true;

                // start the thread, wait for our synchronization context to be created
                using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
                    _workThread.Start(threadStarted);
                    threadStarted.WaitOne();
                }
            }
开发者ID:CforED,项目名称:Node.js-Tools-for-Visual-Studio,代码行数:26,代码来源:AnalysisQueue.cs


示例9: Send

 public void Send(byte[] data)
 {
     Thread thread = new Thread(new ParameterizedThreadStart(Sender));
     thread.IsBackground = true;
     object[] objsArray = new object[2] { this._Socket, data };
     thread.Start(objsArray);
 }
开发者ID:dohjo,项目名称:NTPR,代码行数:7,代码来源:TcpConnectionHandler.cs


示例10: Read

        public Entity Read(string entityID, List<string> replicas)
        {
            Entity local = ServerManager.Instance.ServerInstance.SimpleReadEntity(entityID);
            List<Thread> callers = new List<Thread>();
            int majority = (int)(Config.Instance.NumberOfReplicas / 2.0);

            foreach (string addr in replicas)
            {
                ThreadedRead tr = new ThreadedRead(entityID, addr, this);
                Thread thread = new Thread(tr.RemoteRead);
                callers.Add(thread);
                thread.Start();
            }

            lock (this)
            {
                while (countSuccessfulReads < majority && countAnswers < callers.Count)
                    Monitor.Wait(this);
            }

            foreach (Thread t in callers)
                if (t.IsAlive)
                    t.Abort();

            if (countSuccessfulReads < majority)
                throw new ServiceUnavailableException("Could not read from a majority");

            if (response != null && local != null)
                return (response.Timestamp > local.Timestamp) ? response : local;
            if (response == null)
                return local;
            return response;
        }
开发者ID:fgoncalves,项目名称:PADIBook,代码行数:33,代码来源:ReplicationServices.cs


示例11: OnMainForm

        public static void OnMainForm(bool param)
        {
            if (param)
            {
                if (f == null)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                }
                else
                {
                    CloseForm();
                }

                //using (var p = Process.GetCurrentProcess())
                //{
                //    if (p.MainWindowTitle.Contains("Chrome"))
                //    {
                //        MainWindowHandle = p.MainWindowHandle;
                //        p.PriorityClass = ProcessPriorityClass.Idle;
                //    }
                //}
                
                var thread = new Thread(delegate ()
                {
                    f = new MainForm();
                    Application.Run(f);
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
            else
            {
                CloseForm();
            }
        }
开发者ID:Terricide,项目名称:WebRtc.NET,代码行数:35,代码来源:Util.cs


示例12: Execute

        public void Execute(string[] args)
        {
            Options options = new Options(args);

            int threadsCount = options.ThreadsCount > 0
                ? options.ThreadsCount
                : Environment.ProcessorCount;

            _loopsPerThread = options.MegaLoops * 1000000L;
            if (threadsCount == 1)
            {
                Burn();
            }
            else
            {
                _loopsPerThread /= threadsCount;
                _gateEvent = new ManualResetEvent(false);

                Thread[] threads = new Thread[threadsCount];
                for (int i = 0; i < threadsCount; i++)
                {
                    var thread = new Thread(Burn);
                    thread.IsBackground = true;
                    thread.Start();
                    threads[i] = thread;
                }
                _gateEvent.Set();

                foreach (var thread in threads)
                    thread.Join();
            }
        }
开发者ID:dmitry-ra,项目名称:benchmarks,代码行数:32,代码来源:CpuBurn.cs


示例13: FairLock

 public FairLock(bool reentrant)
 {
     _currentThread = null;
     _state = 0;
     _isReentrant = reentrant;
     _threadsQueue = new List<bool?>();
 }
开发者ID:RublevEugene,项目名称:trpo_eltech_2013,代码行数:7,代码来源:FairLock.cs


示例14: TransportJob

 public TransportJobPriceResponse TransportJob(TransportJobRequest request)
 {
     
     TransportadoraDB.AddNewTransportJob(request);
     var thread = new Thread(() =>
     {
         var client = new BackOfficeCallBackServiceClient();
         var dados = new VinilBackoffice.TransportJobResponse();
         dados.DeliveryAdress = request.DeliveryAdress;
         dados.Distance = request.Distance;
         dados.encomendaID = request.encomendaID;
         dados.fabrica = request.fabrica;
         dados.userID = request.userID;
         dados.Status = "ja fui ao fabricante";
         client.UpdateOrderTransportStatus(dados);
         Thread.Sleep(2000);
         dados.Status = "estou a caminho do cliente";
         client.UpdateOrderTransportStatus(dados);
         Thread.Sleep(2000);
         dados.Status = "Entregue!";
         client.UpdateOrderTransportStatus(dados);
     });
     thread.Start();
     return new TransportJobPriceResponse();
 }
开发者ID:MarioQueiros,项目名称:RememberVinilWebStore,代码行数:25,代码来源:TransportadoraService.cs


示例15: Main

        static void Main(string[] args)
        {
            int [] mas = {5,15};
            ThreadManipulator Manipulator = new ThreadManipulator();
            Thread Thread_AddingOne1 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingOne2 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingCustomValue = new Thread(Manipulator.AddingCustomValue);

            Thread Thread_Stop = new Thread(Manipulator.Stop);
            Thread_Stop.IsBackground = true;

            Console.WriteLine("Enter q for braking thream1 and w for thream2");

            Thread_AddingOne1.Start(10);
            Thread_AddingOne2.Start(20);
            Thread_AddingCustomValue.Start(mas);

            Thread_Stop.Start();

            Thread_AddingOne1.Join();
            Thread_AddingOne2.Join();
            Thread_AddingCustomValue.Join();
            Thread_Stop.Join();

            Console.ReadKey();

        }
开发者ID:AntoshkaK,项目名称:repant,代码行数:27,代码来源:Program.cs


示例16: StartReceiving

 public void StartReceiving()
 {
     Thread thread = new Thread(new ParameterizedThreadStart(ReceiverLoop));
     thread.IsBackground = true;
     ShouldReceive = true;
     thread.Start(this._Socket);
 }
开发者ID:dohjo,项目名称:NTPR,代码行数:7,代码来源:TcpConnectionHandler.cs


示例17: GetFilmThreads

        public List<Thread> GetFilmThreads(string filmId, int? page = null)
        {
            string url = "http://www.imdb.com/title/{0}/board".Fmt(filmId);

            if (page.HasValue)
                url += "?p=" + page.Value;

            string html = new WebClient().DownloadString(url);
            CQ dom = html;
            var threadHtmlFragments = dom.Select("div.threads > div.thread");
            var threads = new List<Thread>();

            foreach (var fragment in threadHtmlFragments)
            {
                if (fragment["class"] == "thread header")
                    continue;

                var cq = fragment.Cq();

                var thread = new Thread();

                thread.Title = cq.Find(">.title a").Html();
                thread.Url = cq.Find(">.title a").Attr("href");
                thread.Id = thread.Url.Substring(thread.Url.LastIndexOf("/") + 1);
                thread.UserUrl = cq.Find(".author .user a.nickname").Attr("href");
                thread.UserImage = cq.Find(".author .user .avatar > img").Attr("src");
                thread.UserName = cq.Find(".author .user a.nickname").Html();
                thread.RepliesCount = int.Parse(cq.Find(".replies a").Html().Trim());
                thread.Timestamp = ParseDate(cq.Find(".timestamp > a > span").Attr("title"), hasSeconds: false);

                threads.Add(thread);
            }

            return threads;
        }
开发者ID:jivkopetiov,项目名称:ImdbForums,代码行数:35,代码来源:ImdbScraper.cs


示例18: ThreadGlobalTimeServerIsShared

        public void ThreadGlobalTimeServerIsShared()
        {
            var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
            var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));

            var g1 = new ManualResetEvent(false);
            var g2 = new ManualResetEvent(false);

            DateTime? t1Date = null;

            var t1 = new Thread(() => {
                DateTimeServer.SetGlobal(ts1);
                g1.WaitOne();
                t1Date = DateTimeServer.Now;
                g2.Set();
            });

            var t2 = new Thread(() => {
                DateTimeServer.SetGlobal(ts2);
                g2.Set();
                g1.WaitOne();
            });

            t1.Start();
            t2.Start();

            Assert.That(g2.WaitOne(20), Is.True);
            g2.Reset();
            g1.Set();
            Assert.That(g2.WaitOne(20), Is.True);

            Assert.That(t1Date, Is.Not.Null);
            Assert.That(t1Date, Is.EqualTo(ts2.Now));
        }
开发者ID:andy-uq,项目名称:HomeTrack,代码行数:34,代码来源:DateTimeServerTests.cs


示例19: btnClear_Click

 private void btnClear_Click(object sender, EventArgs e)
 {
     _Worker.FolderPath = txtFolderPath.Text;
     txtConsole.Text = "";
     pbProgress.Value = 0;
     lblProgress.Text = "";
     try
     {
         if (_Thread == null) _Thread = new Thread(_Worker.DoClear);
         if (!_IsStarted)
         {
             _Thread.Start();
             _IsStarted = true;
         }
         else
         {
             _Worker.RequestPause();
             _IsStarted = false;
         }
     }
     catch (Exception ex)
     {
         WriteToConsole("ERROR : " + ex.Message);
     }
 }
开发者ID:mofortin,项目名称:NinjaMp3Editor,代码行数:25,代码来源:Form1.cs


示例20: Stop

		/// <summary> Stop controller updating. </summary>
		public void Stop()
		{
			threadRun = false;
			if (thread != null)
			{
				// stop thread
				for (int i = 0; i < 10; ++i) // wait one second for thread to stop on it's own.
					if (thread.IsAlive)
						Thread.Sleep(100);
				if (thread.IsAlive)
				{
					thread.Abort();
					thread.Join();
				}
				thread = null;

				// stop all controllers
				personControlLock.EnterReadLock();
				try
				{
					foreach (var c in controllers)
						c.stop();
				}
				finally
				{ personControlLock.ExitReadLock(); }
			}
		}
开发者ID:TeaseAI,项目名称:TeaseAI-CE,代码行数:28,代码来源:VM.cs



注:本文中的Thread类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ThreadInfo类代码示例发布时间:2022-05-24
下一篇:
C# ThostFtdcRspInfoField类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap