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

C# Threading.Thread类代码示例

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

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



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

示例1: Initialize

		// Initialize Parallel class's instance creating required number of threads
		// and synchronization objects
		private void Initialize( )
		{
			threadsCount = System.Environment.ProcessorCount;
			
			//No point starting new threads for a single core computer
			if (threadsCount <= 1) {
				return;
			}
			
			// array of events, which signal about available job
			jobAvailable = new AutoResetEvent[threadsCount];
			// array of events, which signal about available thread
			threadIdle = new ManualResetEvent[threadsCount];
			// array of threads
			threads = new Thread[threadsCount];
		
			for ( int i = 0; i < threadsCount; i++ )
			{
				jobAvailable[i] = new AutoResetEvent( false );
				threadIdle[i]   = new ManualResetEvent( true );
		
				threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
				threads[i].IsBackground = false;
				threads[i].Start( i );
			}
		}
开发者ID:JustSAT,项目名称:Tower-Defence,代码行数:28,代码来源:AstarParallel.cs


示例2: Main

        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("'extractor.exe output_folder input.xef' to extract a .xef file.");
                return;
            }

            string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string subFolderPath = System.IO.Path.Combine(myPhotos, args[0]);
            Directory.CreateDirectory(subFolderPath);

            using (Extractor extractor = new Extractor(subFolderPath))
            {
                extractor.ListenForFrames();

                string xefFileName = args[1];
                Console.WriteLine("Extracting frames from .xef file: {0}", xefFileName);

                Player player = new Player(xefFileName);
                Thread playerThread;
                playerThread = new System.Threading.Thread(new ThreadStart(player.PlayXef));
                playerThread.Start();
                playerThread.Join();

                extractor.Stop();
            }
        }
开发者ID:isalento,项目名称:XefFrameExtractor,代码行数:29,代码来源:Program.cs


示例3: MultiThread

        public void MultiThread()
        {
            int threadCount = 5;
             _threadedMessageCount = 100;
             int totalMessageCount = threadCount * _threadedMessageCount;

             List<Thread> threads = new List<Thread>();
             for (int thread = 0; thread < threadCount; thread++)
             {
            Thread t = new Thread(new ThreadStart(SendMessageThread));

            threads.Add(t);

            t.Start();
             }

             foreach (Thread t in threads)
             {
            t.Join();
             }

             POP3ClientSimulator.AssertMessageCount(_account.Address, "test", totalMessageCount);

             for (int i = 0; i < totalMessageCount; i++)
             {
            string content = POP3ClientSimulator.AssertGetFirstMessageText(_account.Address, "test");

            Assert.IsTrue(content.Contains("X-Spam-Status"), content);
             }
        }
开发者ID:digitalsoft,项目名称:hmailserver,代码行数:30,代码来源:SpamAssassin.cs


示例4: Main

        private static void Main(string[] args)
        {
            var n = 10;

            var chickenFarm = new ChickenFarm();
            var token = chickenFarm.GetToken();
            var chickenFarmer = new Thread(chickenFarm.FarmSomeChickens) {Name = "TheChickenFarmer"};
            var chickenStore = new Retailer(token);
            chickenFarm.PriceCut += chickenStore.OnPriceCut;
            var retailerThreads = new Thread[n];
            for (var index = 0; index < retailerThreads.Length; index++)
            {
                retailerThreads[index] = new Thread(chickenStore.RunStore) {Name = "Retailer" + (index + 1)};
                retailerThreads[index].Start();
                while (!retailerThreads[index].IsAlive)
                {
                    ;
                }
            }
            chickenFarmer.Start();
            chickenFarmer.Join();
            foreach (var retailerThread in retailerThreads)
            {
                retailerThread.Join();
            }
        }
开发者ID:asu-cse445-cornholios,项目名称:Project2,代码行数:26,代码来源:Program.cs


示例5: SetClipboard

 public static void SetClipboard(string result)
 {
     var thread = new Thread(() => Clipboard.SetText(result));
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     thread.Join();
 }
开发者ID:gitter-badger,项目名称:GitReleaseManager,代码行数:7,代码来源:ClipBoardHelper.cs


示例6: SetUp

        public void SetUp()
        {
            runner = new TestRunner(x => x.AddFixture<SlowFixture>());
            test = new Test("slow test").With(Section.For<SlowFixture>().WithStep("GoSlow"));

            var reset = new ManualResetEvent(false);
            var running = new ManualResetEvent(false);

            var thread = new Thread(() =>
            {
                running.Set();
                Debug.WriteLine("Starting to run");
                test.LastResult = runner.RunTest(new TestExecutionRequest()
                {
                    Test = test,
                    TimeoutInSeconds = 60
                });

                test.LastResult.ShouldNotBeNull();
                Debug.WriteLine("finished running");
                reset.Set();
            });

            thread.Start();
            running.WaitOne();
            Thread.Sleep(1000);

            Debug.WriteLine("Aborting now!");
            runner.Abort();
            Debug.WriteLine("Done aborting");

            reset.WaitOne(5000);
            test.LastResult.ShouldNotBeNull();
            Debug.WriteLine("completely done");
        }
开发者ID:wbinford,项目名称:storyteller,代码行数:35,代码来源:AbortTestSmokeTester.cs


示例7: StartService

 public static void StartService()
 {
     Thread thread = new Thread(OrderProcessingService.Run);
     thread.Name = "Order Processing Thread";
     thread.IsBackground = true;
     thread.Start();
 }
开发者ID:michaellperry,项目名称:DuraCore,代码行数:7,代码来源:ServiceConfig.cs


示例8: RelayPort

 public RelayPort(Cpu.Pin pin, bool initialState, bool glitchFilter, Port.ResistorMode resistor, int timeout)
     : base(pin, initialState, glitchFilter, resistor)
 {
     currentstate = initialState;
     relayThread = new Thread(new ThreadStart(RelayLoop));
     relayThread.Start();
 }
开发者ID:mbaldini,项目名称:NovaOS,代码行数:7,代码来源:RelayPort.cs


示例9: Service

 public Service()
 {
     InitializeComponent();
     _server = new ConnectsterServer();
     var job = new ThreadStart(_server.Start);
     _thread = new Thread(job);
 }
开发者ID:shopster,项目名称:NconnectSter,代码行数:7,代码来源:Service.cs


示例10: mainForm

 //UI Init and Main Thread Creation
 public mainForm()
 {
     InitializeComponent();
     AcceptButton = buttonSend;
     tmain = new System.Threading.Thread(main);
     tmain.Start();
 }
开发者ID:Foltik,项目名称:SugoiRC,代码行数:8,代码来源:mainForm.cs


示例11: SetupPrimaryDisplayForm

        /// <summary>
        /// Setups the primary display form.
        /// </summary>
        public static void SetupPrimaryDisplayForm()
        {
            PrimaryDisplayForm = new DisplayForm(800, 600);

            Thread thread = new Thread(new ThreadStart(CreatePrimaryDisplayForm));
            thread.Start();
        }
开发者ID:GeroL,项目名称:MOSA-Project,代码行数:10,代码来源:Setup.cs


示例12: Start

 public void Start()
 {
     Stop();
     m_bThreadStop = false;
     m_thread = new System.Threading.Thread(Main);
     m_thread.Start();
 }
开发者ID:arsaccol,项目名称:SLED,代码行数:7,代码来源:TaskQueue.cs


示例13: Start_WhenExecutedInMultipleThreads_ShouldBeThreadSafeAndNotExecuteSameTaskTwice

        public void Start_WhenExecutedInMultipleThreads_ShouldBeThreadSafeAndNotExecuteSameTaskTwice()
        {
            const string resultId = "result/1";

            Enumerable.Range(1, 100)
                .ToList()
                .ForEach(i =>
                         	{
                         		CreateRaceConditionTask(resultId);
                         		var thread1 = new Thread(() =>
                         		                         	{
                         		                         		var taskExecutor =
                         		                         			MasterResolve<ITaskExecutor>();
                         		                         		taskExecutor.Start();
                         		                         	});
                         		var thread2 = new Thread(() =>
                         		                         	{
                         		                         		var taskExecutor =
                         		                         			MasterResolve<ITaskExecutor>();
                         		                         		taskExecutor.Start();
                         		                         	});

                         		thread1.Start();
                         		thread2.Start();

                         		thread1.Join();
                         		thread2.Join();
                         	});

            var result = Store.Load<ComputationResult<int>>(resultId);

            result.Result.Should().Be(100);
        }
开发者ID:mamluka,项目名称:SpeedyMailer,代码行数:33,代码来源:TaskExecutorTests.cs


示例14: setupRequestResponseBackgroundThead

 private void setupRequestResponseBackgroundThead()
 {
     requestResponseThread = new Thread(new ThreadStart(RequestResponseBackground_Thread));
     requestResponseThread.IsBackground = true;
     multicastRequestThread = new Thread(new ThreadStart(MulticastRequestBackgroud_Thread));
     multicastRequestThread.IsBackground = true;
 }
开发者ID:bdr27,项目名称:c-,代码行数:7,代码来源:App.xaml.cs


示例15: RunInNewThread

 [System.Security.SecurityCritical]  // auto-generated
 private int RunInNewThread () {
     Thread th = new Thread(new ThreadStart(NewThreadRunner));
     th.SetApartmentState(m_apt);
     th.Start();
     th.Join();
     return m_runResult;
 }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:8,代码来源:ApplicationActivator.cs


示例16: Start

 /// <summary>
 /// Starts listening incoming connections.
 /// 
 /// </summary>
 public override void Start()
 {
     this.StartSocket();
     this._running = true;
     this._thread = new Thread(new ThreadStart(this.DoListenAsThread));
     this._thread.Start();
 }
开发者ID:arkanoid1,项目名称:Temu,代码行数:11,代码来源:TcpConnectionListener.cs


示例17: OnCreate

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // set the seed manually.
            OsmSharp.Math.Random.StaticRandomGenerator.Set(116542346);

            // add the to-ignore list.
            OsmSharp.Logging.Log.Ignore("OsmSharp.Osm.Interpreter.SimpleGeometryInterpreter");
            OsmSharp.Logging.Log.Ignore("CHPreProcessor");
            OsmSharp.Logging.Log.Ignore("RTreeStreamIndex");
            OsmSharp.Logging.Log.Ignore("Scene2DLayeredSource");

            // register the textview listener
            OsmSharp.Logging.Log.Enable();
            OsmSharp.Logging.Log.RegisterListener(
                new TextViewTraceListener(this, FindViewById<TextView>(Resource.Id.textView1)));

            // do some testing here.
            Thread thread = new Thread(
                new ThreadStart(Test));
            thread.Start();
        }
开发者ID:nubix-biz,项目名称:OsmSharp,代码行数:26,代码来源:MainActivity.cs


示例18: CheckForLoops

 private static void CheckForLoops(IEnumerable<Activity> activities)
 {
     var isCaughtProperly = false;
     var thread = new System.Threading.Thread(
         () =>
             {
                 try {
                     activities.CriticalPath(p => p.Predecessors, l => (long)l.Duration);
                 }
                 catch (System.InvalidOperationException ex) {
                     System.Console.WriteLine("Found problem: " + ex.Message);
                     isCaughtProperly = true;
                 }
             }
         );
     thread.Start();
     for (var i = 0; i < 100; i++) {
         Thread.Sleep(100); // Wait for 10 seconds - our thread should finish by then
         if (thread.ThreadState != ThreadState.Running)
             break;
     }
     if(thread.ThreadState ==ThreadState.Running)
         thread.Abort();
     System.Console.WriteLine(isCaughtProperly
                                  ? "Critical path caught the loop"
                                  : "Critical path did not find the loop properly");
 }
开发者ID:pourmand,项目名称:amaal,代码行数:27,代码来源:CriticalPathMethod.cs


示例19: ProcessRecord

        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            ExecutionResult result;
            if (Thread.CurrentThread.GetApartmentState() == this.Apartment)
            {
                result = ExecuteExpression(this.Expression);
            }
            else
            {
                var ApartmentThread = new System.Threading.Thread(StartExecuteExpression);
                ApartmentThread.SetApartmentState(this.Apartment);

                var Parameters = new ExecutionParameters { Expression = this.Expression };
                ApartmentThread.Start(Parameters);
                ApartmentThread.Join();

                result = Parameters.Result;
            }
            if (result == null)
                throw new InvalidOperationException("No result returned.");
            if (result.Error != null)
                throw result.Error;
            if (result.Output != null)
                WriteObject(result.Output);
        }
开发者ID:ptownsend1984,项目名称:SampleApplications,代码行数:27,代码来源:InvokeApartmentCommand.cs


示例20: Service

 public Service()
 {
     var filePath = ConfigurationManager.AppSettings["FolderPath"];
     var fileExtension = ConfigurationManager.AppSettings["FileExtension"];
     var dataManager = new DataManager(new Watcher(filePath, fileExtension));
     _workerThread = new Thread(dataManager.OnStart);
 }
开发者ID:andrewtovkach,项目名称:EpamTraining,代码行数:7,代码来源:Service.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Threading.ThreadExceptionEventArgs类代码示例发布时间:2022-05-26
下一篇:
C# Threading.Task类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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