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

C# Task类代码示例

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

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



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


示例16: Start

        /// <summary>
        /// Starts the listening for updates and fires a <see cref="OnMessageReceived"/> event when a message is received.
        /// </summary>
        /// <param name="pollingInterval">The interval of polling in seconds (default set)</param>
        public void Start(int pollingInterval = 1)
        {
            if (_getUpdatesTask != null) return;

            try
            {
                Action poll = async () =>
                {
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        Update[] updates = await GetUpdatesAsync(_lastUpdateId, timeout: pollingInterval);
                        foreach (Update update in updates.Where(u => u.UpdateId > _lastUpdateId))
                        {
                            FireMessageReceived(update.Message);
                            _lastUpdateId = update.UpdateId;
                        }
                        //await Task.Delay(pollingInterval * 1000);
                    }
                };
                _getUpdatesTask = Task.Run(poll, _cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
开发者ID:BAPostma,项目名称:TelegramBot.Net,代码行数:30,代码来源:Bot.Listener.cs


示例17: Add

 public static void Add(RecursiveAsyncLock mutex, Task<IDisposable> key)
 {
     Tuple<int, Task<IDisposable>> value;
     if (!OwnedLocks.TryGetValue(mutex, out value))
         value = Tuple.Create(0, key);
     OwnedLocks = OwnedLocks.SetItem(mutex, Tuple.Create(value.Item1 + 1, value.Item2));
 }
开发者ID:Lakerfield,项目名称:AsyncEx,代码行数:7,代码来源:RecursiveAsyncLockExample.cs


示例18: Main

        static void Main(string[] args)
        {
            var maxPlayers = 6;
            var rand = new Random();

            while (true)
            {

                var numOfPlayers = rand.Next(maxPlayers / 2, maxPlayers);
                Task[] tasks = new Task[numOfPlayers];
                for (int j = 0; j < numOfPlayers; j++)
                {
                    int j1 = j;

                    tasks[j] = Task.Factory.StartNew(() => Target(new ThreadParams()
                                                                      {
                                                                          MaxUsers=numOfPlayers,
                                                                          Seed = j1 * 6,
                                                                          State = (j1 == 0 ? (ThreadState.CreateGame) : ThreadState.JoinGame),
                                                                          UserName = names[j1]
                                                                      }));
                }
                while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

            }
        }
开发者ID:Shuffle-Game,项目名称:ShuffleSlam,代码行数:26,代码来源:Program.cs


示例19: Evaluate

		//called when data for any output pin is requested
		public void Evaluate(int SpreadMax)
		{
			if(FInput.IsChanged)
			{
				FOutput.SliceCount = FInput.SliceCount;
	
				for (int i = 0; i < FInput.SliceCount; i++) {
					
					var r = new TRes();
					r.host = FInput[i];
					r.idx = i;
					r.Resolved = false;
					var t = new Task<TRes>(() => _GetHostByName(r));
					var c = t.ContinueWith((res) =>
					{
					   if(res.Result.ips != null)
					   {
							FOutput[res.Result.idx].SliceCount = res.Result.ips.Length;
							for(int j = 0; j<res.Result.ips.Length;j++)
							{
								FOutput[res.Result.idx][j] = res.Result.ips[j];
							}
						} else FOutput[res.Result.idx].SliceCount = 0;
					},TaskContinuationOptions.OnlyOnRanToCompletion);
					t.Start();
					
					
				}
				
			}
			
			
			//FLogger.Log(LogType.Debug, "Logging to Renderer (TTY)");
		}
开发者ID:zeos,项目名称:VVVV.Plugins,代码行数:35,代码来源:StringHostAddressNode.cs


示例20: CancelAllWhenAnyCompletes

        private static async Task CancelAllWhenAnyCompletes(Task leaderTask, Task renewLeaseTask, CancellationTokenSource cts)
        {
            await Task.WhenAny(leaderTask, renewLeaseTask);

            // Cancel the user's leader task or the renewLease Task, as it is no longer the leader.
            cts.Cancel();

            var allTasks = Task.WhenAll(leaderTask, renewLeaseTask);
            try
            {
                await Task.WhenAll(allTasks);
            }
            catch (Exception)
            {
                if (allTasks.Exception != null)
                {
                    allTasks.Exception.Handle(ex =>
                    {
                        if (!(ex is OperationCanceledException))
                        {
                            Trace.TraceError(ex.Message);
                        }

                        return true;
                    });
                }
            }
        }
开发者ID:mspnp,项目名称:cloud-design-patterns,代码行数:28,代码来源:BlobDistributedMutex.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# TaskCompletionSource类代码示例发布时间:2022-05-24
下一篇:
C# TasSayEventArgs类代码示例发布时间: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