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


C# Task.Start方法代码示例

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


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

示例1: Main

 static void Main()
 {
     Task t = new Task(DownloadPageAsync);
     t.Start();
     Console.WriteLine("Downloading page...");
     Console.ReadLine();
 }
开发者ID:noodle-learns-programming,项目名称:experimental-hq,代码行数:7,代码来源:async-get-url.cs

示例2: Beginning

        public static void Beginning()
        {
            // аналоги вызова метода в потоке из ThreadPool
            // Task даёт бОльшую гибкость
            ThreadPool.QueueUserWorkItem(o => LongRunningMethod());
            new Task(LongRunningMethod).Start();
            Task.Run(() => LongRunningMethod());

            Task<int> t = new Task<int>(LongRunningMethodWithResult);
            t.Start(); // запуск задания

            // блокировка вызвавшего потока до завершения задания
            // однако, если задание ещё не выполняется, вызвавший поток может
            // быть назначен исполнителем задания и он не блокируется
            t.Wait();

            // получение результата выполнения задания
            // свойство Result вызывает метод Wait()
            int result = t.Result;

            // выполнение нового задания по завершении предыдущего
            Task newTask = t.ContinueWith(m => Console.WriteLine(t.Result));

            // блокировка вызвавшего потока, пока не завершатся
            // все / хотя бы один метод из параметров
            Task.WaitAll(t);
            Task.WaitAny(t);
        }
开发者ID:tpltn,项目名称:Parallelism,代码行数:28,代码来源:Tasks.cs

示例3: Main

 public static void Main(String[] args)
 {
     Console.WriteLine("\n-- Cancellation with acknowledgement -------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithAcknowledgement(token), token);
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Wait();    // Throws AggregateException containing TaskCanceledException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Cancellation without acknowledgement ----------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = Task.Run(() => ComputeTaskWithoutAcknowledgement(token), token);
       Thread.Sleep(0);
       Console.WriteLine(task.Status);   // Running
       cts.Cancel();
       Console.WriteLine(task.Status);   // Running
       task.Wait();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
     Console.WriteLine("\n-- Cancellation before Start ---------------------");
     {
       // Cancel before running
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       cts.Cancel();
       Console.WriteLine(task.Status);   // Canceled
       try {
     task.Start();   // Throws InvalidOperationException
       } catch (Exception exn) {
     Console.WriteLine("Caught " + exn);
       }
       Console.WriteLine(task.Status);   // Canceled
     }
     Console.WriteLine("\n-- Completing before cancellation ----------------");
     {
       CancellationTokenSource cts = new CancellationTokenSource();
       CancellationToken token = cts.Token;
       Task task = new Task(delegate { }, token);
       Console.WriteLine(task.Status);   // Created
       task.Start();
       Thread.Sleep(0);  // Allow task to be scheduled
       Console.WriteLine(task.Status);   // RanToCompletion
       cts.Cancel();
       Console.WriteLine(task.Status);   // RanToCompletion
     }
 }
开发者ID:SimonKITU,项目名称:Fsharp,代码行数:60,代码来源:Example174.cs

示例4: demo

    // Runs the demo
    public void demo()
    {

        // Fire off two threads
        Task task1 = new Task(modify);
        Task task2 = new Task(modify);

        task1.Start();
        task2.Start();

        Stopwatch watch = new Stopwatch();
        watch.Start();

        // As long as one of the threads is running, give
        // updates on the value of count
        while (!task1.IsCompleted || !task2.IsCompleted)
        {
            Console.WriteLine("count = " + count);
            Thread.Sleep(10);
        }

        watch.Stop();
        Console.WriteLine("Took: " + watch.ElapsedMilliseconds + " milliseconds");

        // Display the final value of count.  If the threads are well-behaved,
        // it will be zero.
        Console.WriteLine("Final value of count = " + count);
        Console.Read();

    }
开发者ID:jimibue,项目名称:cs3505,代码行数:31,代码来源:Threads1.cs

示例5: Main

    public static void Main()
    {
        Task<Int32[]> parent = new Task<Int32[]>(() => {
            var results = new Int32[3];   // Create an array for the results

            // This tasks creates and starts 3 child tasks
            new Task(() => results[0] = Sum(100), TaskCreationOptions.AttachedToParent).Start();
            new Task(() => results[1] = Sum(200), TaskCreationOptions.AttachedToParent).Start();
            new Task(() => results[2] = Sum(300), TaskCreationOptions.AttachedToParent).Start();

            // Returns a reference to the array
            // (even though the elements may not be initialized yet)
            return results;
        });

        // When the parent and its children have
        // run to completion, display the results
        var cwt = parent.ContinueWith(childTask => Array.ForEach(childTask.Result, Console.WriteLine));

        Console.WriteLine("1. Ready");
        // Start the parent Task so it can start its children
        parent.Start();

        Console.WriteLine("2. Run");

        cwt.Wait();
    }
开发者ID:yielding,项目名称:code,代码行数:27,代码来源:continue2.cs

示例6: Main

    public static void Main(){

        CancellationTokenSource cancelTokenSrc = new CancellationTokenSource();
        
        Task<Int32> t = new Task<Int32>( 
            () => { return Sum(100000000, cancelTokenSrc.Token);},
            cancelTokenSrc.Token);       
        
        t.Start();
        
        cancelTokenSrc.Cancel();
        
        Thread.Sleep(1000);
        
        try{
            Console.WriteLine("Waiting...............");
            t.Wait(); 
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        } 
        try{
            Console.WriteLine("Extracting Result");
            Console.WriteLine("The Sum is: " + t.Result); // An Int32 value            
        }catch(AggregateException ex){        
            ex.Handle(x=> { Console.WriteLine(x.ToString()); return true;});
        }
    }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:27,代码来源:Task.cs

示例7: Main

    public static void Main(){            
        
        Task<Int32[]> parent = new Task<Int32[]>(() => {
                var results = new Int32[3];   // Create an array for the results

                // This tasks creates and starts 3 child tasks
                new Task(() => results[0] = Sum(100), TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[1] = Sum(200), TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[2] = Sum(300), TaskCreationOptions.AttachedToParent).Start();
                
                //Returns reference to the array(even though the elements may not be initialized yet)
                foreach(var result in results)
                    Console.WriteLine("Debug Task: {0}", result);
                return results;
            });
    
        // Start the parent Task so it can start its children
        parent.Start();

        // When the parent and its children have run to completion, display the results
        var cwt = parent.ContinueWith(
            parentTask => {  Console.WriteLine("Debug ContinueWith: "); 
                             Array.ForEach(parentTask.Result, Console.WriteLine);}, 
            TaskContinuationOptions.OnlyOnRanToCompletion);
    
        
        //parent.Wait();
        Thread.Sleep(10000);
    }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:29,代码来源:task-parent-child.cs

示例8: Main

    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        var ct = cts.Token;

        Task task1 = new Task(() => { Run1(ct); }, ct);

        Task task2 = new Task(Run2);

        try
        {
            task1.Start();
            task2.Start();

            Thread.Sleep(1000);

            cts.Cancel();

            Task.WaitAll(task1, task2);
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message);
            }

            //task1是否取消
            Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
            Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
        }

        Console.Read();
    }
开发者ID:dalinhuang,项目名称:wdeqawes-efrwserd-rgtedrtf,代码行数:34,代码来源:Program.cs

示例9: DeviceAccession

        public DeviceAccession()
        {
            //Az attributumok elérésénél a lockhoz a szinkronizációs objektum
            lockAttributes = new object();

            DAQ = DaqSystem.Local.LoadDevice("Dev1");
            DAQ.SelfCalibrate();

            ditask = new Task();
            dotask = new Task();
            aitask = new Task();

            chLeftEnd = ditask.DIChannels.CreateChannel("Dev1/port0/line0", "Left End", ChannelLineGrouping.OneChannelForEachLine);
            chRightEnd = ditask.DIChannels.CreateChannel("Dev1/port0/line1", "Right End", ChannelLineGrouping.OneChannelForEachLine);

            chMoveToLeft = dotask.DOChannels.CreateChannel("Dev1/port1/line0", "Move to the Left", ChannelLineGrouping.OneChannelForEachLine);
            chMoveToRight = dotask.DOChannels.CreateChannel("Dev1/port1/line1", "Move to the Right", ChannelLineGrouping.OneChannelForEachLine);

            chAngle = aitask.AIChannels.CreateVoltageChannel("Dev1/ai0", "Angle", AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);
            chPosition = aitask.AIChannels.CreateVoltageChannel("Dev1/ai1", "Position", AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);

            ditask.Start();
            dotask.Start();
            aitask.Start();

            digreader = new DigitalMultiChannelReader(ditask.Stream);
            digwriter = new DigitalMultiChannelWriter(dotask.Stream);
            anreader = new AnalogMultiChannelReader(aitask.Stream);
        }
开发者ID:robert-fekete,项目名称:ControllerArchitect,代码行数:29,代码来源:DeviceAccession.cs

示例10: StartTask

 public Task StartTask(IEnumerator coroutine, bool autoStart = true, UnityAction finishedHandle = null)
 {
     var r = new Task(coroutine);
     r.FinishedHandle = finishedHandle;
     if (autoStart) r.Start();
     return r;
 }
开发者ID:meta-42,项目名称:uEasyKit,代码行数:7,代码来源:TaskManager.cs

示例11: Task1

 static void Task1()
 {
     Thread.CurrentThread.Name = "Main";
     // Create a task and supply a user delegate by using a lambda expression.
     Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
     taskA.Start();
     Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name);
     taskA.Wait();
 }
开发者ID:walrus7521,项目名称:code,代码行数:9,代码来源:Tasks.cs

示例12: ChildTasks

        // задания могут иметь отношение Родительское <=> Дочерние
        // по-умолчанию, все одноранговые
        public static void ChildTasks()
        {
            Task task = new Task(() =>
            {
                Console.WriteLine("Hello from parent task!");
                new Task(() => Console.WriteLine("Hello from child task!"), TaskCreationOptions.AttachedToParent).Start();
            });

            task.Start();
        }
开发者ID:tpltn,项目名称:Parallelism,代码行数:12,代码来源:Tasks.cs

示例13: Main

 static void Main(string[] args) {
     Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
     Task t = new Task(() =>
     {
         Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
     });
     t.Start();
     t.Wait();
     Console.ReadLine();
 }
开发者ID:Geronimobile,项目名称:DotNetExamIntro,代码行数:10,代码来源:Program.cs

示例14: Main

    static void Main(string[] args)
    {
		string decorationLine = new string('-', Console.WindowWidth);
		Console.Write(decorationLine);
		Console.WriteLine("***PubNub simple chat application***");
		Console.Write(decorationLine);
	
        Process.Start("..\\..\\RecieverPage.html");

        Thread.Sleep(2000);

        PubnubAPI pubnub = new PubnubAPI(
            "pub-c-d9aadadf-abba-443c-a767-62023d43411a",               // PUBLISH_KEY
            "sub-c-102d0358-073f-11e3-916b-02ee2ddab7fe",               // SUBSCRIBE_KEY
            "sec-c-YmI4NDcxNzQtOWZhYi00MTRmLWI4ODktMDI2ZjViMjQyYzdj",   // SECRET_KEY
            false                                                       // SSL_ON/OFF
        );

        string channel = "PublishApp";

        // Publish a sample message to Pubnub
        List<object> publishResult = pubnub.Publish(channel, "Hello PubNub!");
        Console.WriteLine(
            "Publish Success: " + publishResult[0].ToString() + "\n" +
            "Publish Info: " + publishResult[1]
        );

        // Show PubNub server time
        object serverTime = pubnub.Time();
        Console.WriteLine("Server Time: " + serverTime.ToString());

        // Subscribe for receiving messages (in a background task to avoid blocking)
        Task task = new Task(
            () =>
            pubnub.Subscribe(
                channel,
                delegate(object message)
                {
                    Console.WriteLine("Received Message -> '" + message + "'");
                    return true;
                }
            )
        );

        task.Start();

        // Read messages from the console and publish them to PubNub
        while (true)
        {
            Console.Write("Enter a message to be sent to Pubnub: ");
            string msg = Console.ReadLine();
            pubnub.Publish(channel, msg);
            Console.WriteLine("Message {0} sent.", msg);
        }
    }
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:55,代码来源:PubNubChat.cs

示例15: SetUp

        public void SetUp()
        {
            DateTimeHelper.Fix();

            _task = new Task();

            GoToInitialState(_task);

            DateTimeHelper.MoveAheadBy(TimeSpan.FromSeconds(50));

            _task.Start();
        }
开发者ID:ArildF,项目名称:PTB,代码行数:12,代码来源:When_setting_a_task_back_to_InProgress.cs


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