当前位置: 首页>>代码示例>>C#>>正文


C# Task.Wait方法代码示例

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


在下文中一共展示了Task.Wait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Action

        public void Action(RoomItem Item, Task Task, string ExtraData)
        {
            if (ExtraData == "1")
            {
                Task.Wait(7000);
                Item.FireWorkCount--;

                using (DatabaseClient dbClient = GoldTree.GetDatabase().GetClient())
                {
                    dbClient.AddParamWithValue("itemid", Item.uint_0);
                    dbClient.ExecuteQuery("UPDATE items SET fw_count = fw_count - 1 WHERE id = @itemid LIMIT 1");
                }
            }

            if (Item.FireWorkCount == 0)
            {
                ExtraData = "0";
            }

            Item.ExtraData = ExtraData;
            Item.UpdateState(true, true);

            Task.Wait();
            Task.Dispose();
        }
开发者ID:ArneVanDaele,项目名称:GoldenTreeEMU,代码行数:25,代码来源:InteractorFirework.cs

示例2: DoubleTimeoutedWaitTest

        public void DoubleTimeoutedWaitTest()
        {
            var evt = new ManualResetEventSlim();
            var t = new Task(delegate { });
            var cntd = new CountdownEvent(2);

            bool r1 = false, r2 = false;
            ThreadPool.QueueUserWorkItem(delegate { r1 = !t.Wait(100); cntd.Signal(); });
            ThreadPool.QueueUserWorkItem(delegate { r2 = !t.Wait(100); cntd.Signal(); });

            cntd.Wait(2000);
            Assert.IsTrue(r1);
            Assert.IsTrue(r2);
        }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:14,代码来源:MinimalTaskTests.cs

示例3: Execute

        public void Execute(Action<IActorRuntime, ITestingRuntime> action, IScheduler scheduler)
        {
            runtime = new TestingActorRuntime(scheduler);

            // TODO: Remove this somehow.
            TaskHelper.runtime = runtime;

            var task = new Task(() =>
            {
                TestingActorRuntime.ActorBody<object>(
                    () =>
                    {
                        action(runtime, runtime);
                        return null;
                    },
                    runtime,
                    true);
            },
                CancellationToken.None,
                TaskCreationOptions.RunContinuationsAsynchronously);

            runtime.RegisterMainTask(task);

            task.Start(taskScheduler);

            task.Wait();
            runtime.WaitForAllActorsToTerminate();
        }
开发者ID:paulthomson,项目名称:adara-actors,代码行数:28,代码来源:TestLauncher.cs

示例4: MultiRunGPUGravityModel

 public MultiRunGPUGravityModel(int length, Action<float> progressCallback = null, float epsilon = 0.8f, int maxIterations = 100)
 {
     var programPath = Assembly.GetEntryAssembly().CodeBase.Replace( "file:///", String.Empty );
     try
     {
         this.gpu = new GPU();
     }
     catch
     {
         throw new XTMFRuntimeException( "Unable to create a connection to the GPU, please make sure you are using a DirectX11+ card!" );
     }
     Task initialize = new Task( delegate()
         {
             this.length = length;
             this.ProgressCallback = progressCallback;
             this.Epsilon = epsilon;
             this.MaxIterations = maxIterations;
             CreateBuffers();
         } );
     initialize.Start();
     // while everything else is being initialized, compile the shader
     this.gravityModelShader = gpu.CompileComputeShader( Path.Combine( Path.GetDirectoryName( programPath ), "Modules", "GravityModel.hlsl" ), "CSMain" );
     initialize.Wait();
     if ( this.gravityModelShader == null )
     {
         throw new XTMFRuntimeException( "Unable to compile GravityModel.hlsl!" );
     }
 }
开发者ID:Cocotus,项目名称:XTMF,代码行数:28,代码来源:MultiRunGPUGravityModel.cs

示例5: Compiler_Analyze_SimpleModule

        public void Compiler_Analyze_SimpleModule()
        {
            using (var tester = new CompilerTester(nameof(Compiler_Analyze_SimpleModule), Source))
            {
                var compiler = tester.Compiler;
                var context = compiler.Context;
                var compileUnit = context.CompileUnits.First();
                var sourceFile = compileUnit.SourceFiles.First();
                var parseUnit = new ParseUnit { SourceFile = sourceFile };

                var parse = new Task(new ParseSourceFile(context, parseUnit).GetStepAction(context.CancelSource.Token));
                parse.Start();
                parse.Wait();
                Assert.AreEqual(0, compileUnit.Errors.Count(), "parse errors: " + string.Join("; ", compileUnit.Errors.Select(e => e.Message)));

                var analyzeUnit = new AnalysisUnit { ParseUnits = new List<ParseUnit>() { parseUnit } };
                var analyze = new Task(new AnalyzeSourceFile(context, analyzeUnit, parseUnit).GetStepAction(context.CancelSource.Token));
                analyze.Start();
                analyze.Wait();

                Assert.AreEqual(0, compileUnit.Errors.Count(), "analyze errors: " + string.Join("; ", compileUnit.Errors.Select(e => e.Message)));

                var module = analyzeUnit.Modules.Values.Single(m => m.Name.Name == "One");
                var binding = module.Bindings.Values.Single(b => b.Name.Name == "f");
                Assert.IsFalse(binding.IsPublic);

                Assert.IsInstanceOfType(binding.Expression, typeof(Analyze.Expressions.IntegerLiteral));
                var intLiteral = binding.Expression as Analyze.Expressions.IntegerLiteral;

                Assert.IsInstanceOfType(intLiteral.ResolvedType, typeof(Analyze.Builtins.SystemInt32));
                var val = (int)intLiteral.IntValue;
                Assert.AreEqual(123, val);
            }
        }
开发者ID:apterid,项目名称:apterid-bootstrap,代码行数:34,代码来源:SimpleModuleTests.cs

示例6: Stop

 public void Stop(HttpListener listener, Task handleRequests, Task updateWorld)
 {
     _exiting = true;
     listener.Stop();
     updateWorld.Wait(TimeSpan.FromSeconds(2));
     handleRequests.Wait(TimeSpan.FromSeconds(2));
 }
开发者ID:vvnurmi,项目名称:MOOLGOSS,代码行数:7,代码来源:Server.cs

示例7: GetStatus

        private void GetStatus(Task<UploadResponse> task)
        {
            task.Wait();

            var uuid = task.Result.Uuid;
            
            Console.WriteLine("Document uuid is: {0}", uuid);

            var status = DocumentStatus.Queued;

            do
            {
                var statusTask = _document.GetStatusAsync(uuid);
                statusTask.Wait();

                var result = statusTask.Result;
                uuid = result.Uuid;
                status = result.Status;

                Console.WriteLine("{2:o} Document uuid {0} status is: {1}", uuid, status, DateTime.Now);

                if (status == DocumentStatus.Queued || status == DocumentStatus.Processing)
                {
                    Task.Delay(TimeSpan.FromSeconds(1)).Wait();
                }
            }
            while (status == DocumentStatus.Queued || status == DocumentStatus.Processing);

            Delete(uuid);
        }
开发者ID:pbolduc,项目名称:Crocodoc.NET,代码行数:30,代码来源:CrocodocDocumentTests.cs

示例8: Execute

        public void Execute()
        {
            //
            // 入れ子タスクの作成
            //
            // タスクは入れ子にすることも可能。
            //
            // 入れ子のタスクには、以下の2種類が存在する。
            //   ・単純な入れ子タスク(デタッチされた入れ子タスク)
            //   ・子タスク(親のタスクにアタッチされた入れ子タスク)
            //
            // 以下のサンプルでは、子タスクを作成して実行している。
            // 子タスクとは、単純な入れ子タスクと違い、親タスクと親子関係を
            // 持った状態でタスク処理が行われる。
            //
            // つまり、親のタスクは子のタスクの終了を待ってから、自身の処理を終了する。
            //
            // 親との関連を持つ入れ子のタスクは、「アタッチされた入れ子のタスク」と言う。
            //
            // アタッチされた入れ子タスクの作成は、タスクを生成する際に以下のTaskCreationOptionsを
            // 指定する。
            //   TaskCreationOptions.AttachedToParent
            //

            //
            // 親子関係を持つ子タスクを作成.
            //
            Output.WriteLine("親のタスク開始");
            var t = new Task(ParentTaskProc);
            t.Start();
            t.Wait();
            Output.WriteLine("親のタスク終了");
        }
开发者ID:devlights,项目名称:Sazare,代码行数:33,代码来源:TaskSamples04.cs

示例9: Main

        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Verwendung: RisCmd NORxxxxx");
            }

            string dokumentNummer = args[0];

            var task = new Task<DocumentResult>(() => DocumentLoadTask.LoadAsync(dokumentNummer).Result);
            task.Start();
            task.Wait();

            var result = task.Result;

            if (result.Succeeded)
            {
                string fileName = dokumentNummer + ".xml";
                File.WriteAllText(fileName, result.OriginalDocumentResultXml);

                Console.WriteLine(fileName + " erfolgreich lokal gespeichert");
            }
            else
            {
                Console.WriteLine("Dokument konnte nicht geladen werden, Fehlermeldung: ");
                Console.WriteLine(result.Error);
            }
        }
开发者ID:christophwille,项目名称:winrt-ris,代码行数:28,代码来源:Program.cs

示例10: BindAndConnect

        public void BindAndConnect()
        {
            // setup a stub model, expect initialize is called
            const string configFile = "test.config";
            var model = MockRepository.GenerateStub<IBasicModelInterface>();
            model.Expect(m => m.Initialize(Arg<string>.Is.Equal(configFile))).Return(0);
            model.Expect(m => m.Finish()).Return(0);

            // start server and connect client to it, call Initialize on client
            using (var runner = new MmiModelRunner(connectionString, model))
            using (var client = new MmiModelClient(connectionString))
            {
                runner.Bind();
                client.Connect();

                // start message loop on server
                var serverTask = new Task(() => runner.Start());
                serverTask.Start();

                // initialize
                client.Initialize(configFile);
                client.Finish();

                // stop server
                serverTask.Wait();
            }

            // validate
            model.VerifyAllExpectations();
        }
开发者ID:MischaJ,项目名称:mmi-csharp,代码行数:30,代码来源:MmiModelClientServerTest.cs

示例11: Should_be_able_to_cancel_message_reception_upon_disposal

        public void Should_be_able_to_cancel_message_reception_upon_disposal()
        {
            const string mmfName = "Local\\test";
            var message = "not null";
            var messageCancelled = new EventWaitHandle(false, EventResetMode.ManualReset, mmfName + "_MessageCancelled");

            messageCancelled.Set();

            var messageReceiver = new MemoryMappedFileMessageReceiver(mmfName);

            var task = new Task(() => message = messageReceiver.ReceiveMessage(ReadString));

            task.Start();

            var isSet = true;

            while (isSet)
                isSet = messageCancelled.WaitOne(0);

            messageReceiver.Dispose();

            task.Wait();

            message.ShouldBeNull();
        }
开发者ID:kushniro,项目名称:MemoryMessagePipe,代码行数:25,代码来源:Tests.cs

示例12: GA

        public GA(int genomeLength, int populationSize, Func<double[], int, bool, double> fitnessFunction)
        {
            Population = new List<Species>(populationSize);
            FitnessFunction = fitnessFunction;
            PopulationSize = populationSize;

            for (int i = 0; i < populationSize; i++)
                Population.Add(new Species(genomeLength));

            List<Task> tasks = new List<Task>();

            foreach (Species s in Population)
            {
                int pidd = pid++;
                Task t = new Task(() =>
                {
                    s.Fitness = FitnessFunction(s.Genome, pidd, true);
                });
                tasks.Add(t);
                t.Start();
            }
            tasks.ForEach(t => t.Wait());

            Population.Sort((s, t) => t.Fitness.CompareTo(s.Fitness));
        }
开发者ID:mattsains,项目名称:WRCIComponentChooser,代码行数:25,代码来源:GA.cs

示例13: Connect

        //connects to irc server, gives a boolean back on succesfull connect etc
        public bool Connect()
        {
            try
            {
                irc = new TcpClient(newIP, newPort);
                stream = irc.GetStream();

                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);

                ping = new Pinger(simpleirc, this);
                ping.Start();

                writeIrc("USER " + newUsername + " 8 * : Testing RareAMVS C# irc client");
                writeIrc("NICK " + newUsername);
                writeIrc("JOIN " + newChannel);

                simpleirc.DebugCallBack("succesful connected to the irc server!");

                receiverTask = new Task(StartReceivingChat);
                receiverTask.Start();
                receiverTask.Wait();
                return true;
            }
            catch(Exception e)
            {
                simpleirc.DebugCallBack("Error Connecting to IRC Server: \n " + e.ToString());
                return false;
            }
        }
开发者ID:EldinZenderink,项目名称:SimpleIRCLib,代码行数:31,代码来源:IrcConnect.cs

示例14: _GetBufferedDataFeed

        static IEnumerable<DataSample> _GetBufferedDataFeed(iRacingConnection iRacingConnection, int maxBufferLength)
        {
            var que = new ConcurrentQueue<DataSample>();
            bool cancelRequest = false;

            var t = new Task(() => EnqueueSamples(que, iRacingConnection, maxBufferLength, ref cancelRequest));
            t.Start();

            try
            {
                DataSample data;

                while (true)
                {
                    if (que.TryDequeue(out data))
                        yield return data;
                }
            }
            finally
            {
                cancelRequest = true;
                t.Wait(200);
                t.Dispose();
            }
        }
开发者ID:RobRobertsCE,项目名称:iRacingSolution,代码行数:25,代码来源:GetBufferedDataFeed.cs

示例15: Should_have_thread_safe_publish

        public void Should_have_thread_safe_publish()
        {
            ulong sequenceNumber = 0;
            channel.Stub(x => x.NextPublishSeqNo).Do(new Func<ulong>(() => sequenceNumber++));

            const int repeat = 100000;
            var register = new Task(() =>
            {
                for (int i = 0; i < repeat; ++i)
                {
                    var tag = i;

                    publisherConfirms.RegisterCallbacks(channel, () => { }, () => { });

                    Task.Factory.StartNew(() => publisherConfirms.SuccessfulPublish(channel, new BasicAckEventArgs
                    {
                        DeliveryTag = (ulong)tag
                    }), TaskCreationOptions.AttachedToParent);
                }
            });

            register.Start();
            register.Wait();

            Assert.That(publisherConfirms.NumCallbacks, Is.EqualTo(0));
        }
开发者ID:richard-green,项目名称:EasyNetQ,代码行数:26,代码来源:PublisherConfirmsTests.cs


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