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


C# Task类代码示例

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


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

示例1: Validate

        public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
        {
            var tasks = new List<Task<IYubicoResponse>>();
            var cancellation = new CancellationTokenSource();

            foreach (var url in urls)
            {
                var thisUrl = url;
                var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
                task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                tasks.Add(task);
                task.Start();
            }

            while (tasks.Count != 0)
            {
                // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
                var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
                var task = tasks[completed];
                tasks.Remove(task);
                if (task.Result != null)
                {
                    cancellation.Cancel();
                    return task.Result;
                }
            }

            return null;
        }
开发者ID:Yubico,项目名称:yubico-dotnet-client,代码行数:29,代码来源:YubicoValidate.cs

示例2: CommandProcessor

        public CommandProcessor(ICommandProcessingStrategy processingStrategy,
                                ICommandQueue commandQueue)
        {
            _processingStrategy = processingStrategy;
            _commandQueue = commandQueue;

            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
            var task = new Task(
                () =>
                    {
                        while (!token.IsCancellationRequested)
                        {
                            var cmd = _commandQueue.Dequeue();
                            while (cmd != null)
                            {
                                _processingStrategy.ProcessCommand(cmd.Execute);
                                cmd = commandQueue.Dequeue();
                            }
                            Thread.Sleep(100);
                        }
                    },
                token,
                TaskCreationOptions.LongRunning);
            task.Start();
        }
开发者ID:naziway,项目名称:testtask,代码行数:26,代码来源:CommandProcessor.cs

示例3: AsynchronousTraceListenerWrapper

        /// <summary>
        /// Initializes a new instance of the <see cref="AsynchronousTraceListenerWrapper" /> class.
        /// </summary>
        /// <param name="wrappedTraceListener">The wrapped trace listener.</param>
        /// <param name="ownsWrappedTraceListener">Indicates whether the wrapper should dispose the wrapped trace listener.</param>
        /// <param name="bufferSize">Size of the buffer for asynchronous requests.</param>
        /// <param name="maxDegreeOfParallelism">The max degree of parallelism for thread safe listeners. Specify <see langword="null"/> to use the current core count.</param>
        /// <param name="disposeTimeout">The timeout for waiting to complete buffered requests when disposing. When <see langword="null" /> the default of <see cref="Timeout.InfiniteTimeSpan" /> is used.</param>
        public AsynchronousTraceListenerWrapper(
            TraceListener wrappedTraceListener,
            bool ownsWrappedTraceListener = true,
            int? bufferSize = DefaultBufferSize,
            int? maxDegreeOfParallelism = null,
            TimeSpan? disposeTimeout = null)
        {
            Guard.ArgumentNotNull(wrappedTraceListener, "wrappedTraceListener");
            CheckBufferSize(bufferSize);
            CheckMaxDegreeOfParallelism(maxDegreeOfParallelism);
            CheckDisposeTimeout(disposeTimeout);

            this.wrappedTraceListener = wrappedTraceListener;
            this.ownsWrappedTraceListener = ownsWrappedTraceListener;
            this.disposeTimeout = disposeTimeout ?? Timeout.InfiniteTimeSpan;

            this.closeSource = new CancellationTokenSource();
            this.requests = bufferSize != null ? new BlockingCollection<Action<TraceListener>>(bufferSize.Value) : new BlockingCollection<Action<TraceListener>>();

            if (this.wrappedTraceListener.IsThreadSafe)
            {
                this.maxDegreeOfParallelism = maxDegreeOfParallelism.HasValue ? maxDegreeOfParallelism.Value : Environment.ProcessorCount;
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequestsInParallel, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            else
            {
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequests, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }
开发者ID:Brar,项目名称:entlib,代码行数:37,代码来源:AsynchronousTraceListenerWrapper.cs

示例4: Promise

 public Promise(Arguments args)
 {
     m_promiseTask = new Task<JSObject>(() =>
     {
         return Undefined;
     });
 }
开发者ID:Oceanswave,项目名称:SkraprSharp,代码行数:7,代码来源:Promise.cs

示例5: AddOnChangeSetFailureTask

		public void AddOnChangeSetFailureTask(Task onFailureTask)
		{
			lock (this)
			{
				_onFailureTasks.Add(onFailureTask);
			}
		}
开发者ID:mdabbagh88,项目名称:ODataServer,代码行数:7,代码来源:ChangeSetContext.cs

示例6: Disable

            public void Disable()
            {
                lock (_gate)
                {
                    if (_instanceTask == null)
                    {
                        // already disabled
                        return;
                    }

                    var instance = _instanceTask;
                    _instanceTask = null;

                    RemoveGlobalAssets();

                    _shutdownCancellationTokenSource.Cancel();

                    try
                    {
                        instance.Wait(_shutdownCancellationTokenSource.Token);

                        instance.Result.Shutdown();
                    }
                    catch (OperationCanceledException)
                    {
                        // _instance wasn't finished running yet.
                    }
                }
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:29,代码来源:RemoteHostClientServiceFactory.RemoteHostClientService.cs

示例7: NUnitTestShouldDependOnDlls

        public void NUnitTestShouldDependOnDlls()
        {
            var paths = new Task<string> [] {"one", "two"};
            var tests = new NUnitTests {DllPaths = paths};

            Assert.That(tests.Dependencies.Select(d => d.Task), Has.Member(paths[0]).And.Member(paths[1]));
        }
开发者ID:jdomzhang,项目名称:bounce,代码行数:7,代码来源:TaskTest.cs

示例8: Start

		public static void Start(string name)
		{
			DBC.Pre(!string.IsNullOrEmpty(name), "name is null or empty");
			
			if (ms_current == null)
			{
				DBC.Assert(ms_root == null, "Start was called after the root task was stopped");
				
				ms_root = new Task(null, name);
				ms_current = ms_root;
			}
			else
			{
				Task task;
				if (!ms_current.SubTasks.TryGetValue(name, out task))
				{
					task = new Task(ms_current, name);
					ms_current.SubTasks.Add(name, task);
				}
				else
				{
					DBC.Assert(task.StartTime == DateTime.MinValue, "can't nest the same task");
					task.StartTime = DateTime.Now;
					task.Count += 1;
				}
				ms_current = task;
			}			
		}
开发者ID:dbremner,项目名称:smokey,代码行数:28,代码来源:Profile.cs

示例9: Save

		public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
		{
			_metrics = metrics;

			OpenFiles();

			var saveTasks = new Task[4];

			saveTasks[0] = SaveItems();
			saveTasks[1] = SaveMobiles();
			saveTasks[2] = SaveGuilds();
			saveTasks[3] = SaveData();

			SaveTypeDatabases();

			if (permitBackgroundWrite)
			{
				//This option makes it finish the writing to disk in the background, continuing even after Save() returns.
				Task.Factory.ContinueWhenAll(
					saveTasks,
					_ =>
					{
						CloseFiles();

						World.NotifyDiskWriteComplete();
					});
			}
			else
			{
				Task.WaitAll(saveTasks); //Waits for the completion of all of the tasks(committing to disk)
				CloseFiles();
			}
		}
开发者ID:jasegiffin,项目名称:JustUO,代码行数:33,代码来源:DynamicSaveStrategy.cs

示例10: TryExecuteTaskInline

			protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
			{
				if (TryExecuteTaskInlineHandler != null)
					TryExecuteTaskInlineHandler (task, taskWasPreviouslyQueued);

				return base.TryExecuteTask (task);
			}
开发者ID:GirlD,项目名称:mono,代码行数:7,代码来源:TaskTest.cs

示例11: Start

 public void Start()
 {
     if (_running)
         return;
     _running = true;
     _httpTask = Task.Run(() => RunTask(), _cts.Token);
 }
开发者ID:DynamicDevices,项目名称:Example-02-WebServer,代码行数:7,代码来源:HttpHandler.cs

示例12: AsincronismoConTpl

        /// <summary>
        /// Implementación para la demostración del flujo de control de invocaciones 
        /// a través de elementos de programa de TPL.
        /// </summary>
        /// <returns>Resultado de la operación asincrónica.</returns>
        private Task AsincronismoConTpl()
        {
            var tareaCompuesta = new Task(() =>
            {
                Task<string> tarea1 = ObtenerInfoThreadAsync("TPL No. 1");
                tarea1.ContinueWith(tarea =>
                {
                    Console.WriteLine(tarea1.Result);

                    Task<string> tarea2 = ObtenerInfoThreadAsync("TPL No. 2");
                    tarea2.ContinueWith(tareaAnidada =>
                        Console.WriteLine(tareaAnidada.Result),
                        TaskContinuationOptions.NotOnFaulted |
                            TaskContinuationOptions.AttachedToParent);

                    tarea2.ContinueWith(tareaAnidada =>
                        Console.WriteLine(tareaAnidada.Exception.InnerException),
                        TaskContinuationOptions.OnlyOnFaulted |
                            TaskContinuationOptions.AttachedToParent);
                },
                    TaskContinuationOptions.NotOnFaulted |
                        TaskContinuationOptions.AttachedToParent);

                tarea1.ContinueWith(tarea =>
                    Console.WriteLine(tarea1.Exception.InnerException),
                    TaskContinuationOptions.OnlyOnFaulted |
                        TaskContinuationOptions.AttachedToParent);
            });

            tareaCompuesta.Start();

            return tareaCompuesta;
        }
开发者ID:Fhernd,项目名称:RecetasMultithreadingCSharp,代码行数:38,代码来源:TareasAsincronicasConsecutivas.cs

示例13: Stop

        public async Task Stop()
        {
            await _startStopSemaphore.WaitAsync();

            try
            {
                if (!_running) return;
                _running = false;

                _cancellationTokenSource.Cancel();
                _cancellationTokenSource = null;

                var workerTask = _workerTask;
                _workerTask = null;
                if (workerTask != null) await workerTask;

                // wait for all our existing tasks to complete
                //FIXME a bit ick..
                while (_throttle.CurrentCount < ConcurrentHandlerLimit)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(100));
                }
            }
            finally
            {
                _startStopSemaphore.Release();
            }
        }
开发者ID:AtmosphereMessaging,项目名称:Cumulus,代码行数:28,代码来源:ThrottlingMessageReceiver.cs

示例14: QueueTask

			protected override void QueueTask (Task task)
			{
				Interlocked.Increment (ref qc);
				ThreadPool.QueueUserWorkItem (o => {
					TryExecuteTask (task);
				});
			}
开发者ID:nlhepler,项目名称:mono,代码行数:7,代码来源:TaskAwaiterTest.cs

示例15: DropDownListMark_SelectedIndexChanged

    protected void DropDownListMark_SelectedIndexChanged(object sender, EventArgs e)
    {
        bool status = false;
        foreach (GridViewRow row in GridViewTask.Rows)
        {
            CheckBox checkBox = (CheckBox)row.Cells[0].FindControl("CheckBoxTask");
            if (checkBox.Checked)
            {
                HiddenField hiddenField = (HiddenField)row.Cells[0].FindControl("HiddenFieldTask");
                string taskUserOID = hiddenField.Value;
                Task task = new Task();
                if ((DropDownListMark.SelectedItem.Text == "Mark") || (DropDownListMark.SelectedItem.Text == "Star"))
                {
                    if (task.UpdateTaskUserUMark(Convert.ToInt32(taskUserOID), 1)) status = true;
                }
                else
                {
                    if (task.UpdateTaskUserUStatus(Convert.ToInt32(taskUserOID), DropDownListMark.SelectedItem.Text)) status = true;
                }

            }
        }
        if (status)
        {
            PopulateGridview();
        }
    }
开发者ID:mominbd,项目名称:testing,代码行数:27,代码来源:ViewTask.aspx.cs


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