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


C# Tasks.Task类代码示例

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


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

示例1: button1_Click

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // For best results use 1024 x 768 jpg files at 32bpp.
            string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures\", "*.jpg");

            _fileCount = files.Length;
            var loadImageTasks = new Task<byte[]>[_fileCount];

            // Spin off a task to load each image
            for (var i = 0; i < _fileCount; i++)
            {
                var x = i;
                loadImageTasks[x] = Task.Factory.StartNew(() => LoadImage(files[x]));
            }

            // When they've all been loaded, tile them into a single byte array.
            var tiledImageTask = Task.Factory.ContinueWhenAll(loadImageTasks, i => TileImages(i));

            // We are currently on the UI thread. Save the sync context and pass it to
            // the next task so that it can access the UI control "image1".
            var uiSyncContext = TaskScheduler.FromCurrentSynchronizationContext();

            // On the UI thread, put the bytes into a bitmap and
            // and display it in the Image control.
            tiledImageTask.ContinueWith(antedecent => LoadTiledImage(antedecent.Result), uiSyncContext);
        }
开发者ID:srstrong,项目名称:DDDSW2010,代码行数:26,代码来源:MainWindow.xaml.cs

示例2: OnBeginRequest

        private static void OnBeginRequest(object sender, EventArgs e) {
            var context = (HttpApplication)sender;

            // TaskCreationOptions.PreferFairness 를 지정해야, StartNew() 메소드를 바로 시작한다.
            var stopwatchTask
                = new Task<Lazy<double>>(() => {
                                             var sw = new Stopwatch();
                                             sw.Start();

                                             if(IsDebugEnabled) {
                                                 var request = context.Request;
                                                 log.Debug(BeginRequestLogFormat,
                                                           request.UserHostAddress,
                                                           request.RequestType,
                                                           request.CurrentExecutionFilePath);
                                             }

                                             // Lazy 값을 처음 호출할 때, stop watch가 끝나고, 경과 값을 반환한다.
                                             return new Lazy<double>(() => {
                                                                         sw.Stop();
                                                                         return sw.ElapsedMilliseconds;
                                                                     });
                                         });
            stopwatchTask.Start();

            Local.Data[AsyncAccessLogModuleKey] = stopwatchTask;
        }
开发者ID:debop,项目名称:NFramework,代码行数:27,代码来源:AsyncAccessLogModule.cs

示例3: Execute

 public async void Execute(object parameter)
 {
     asyncExecutingTask = this.asyncExecute();
     await asyncExecutingTask;
     asyncExecutingTask = null;
     CommandManager.InvalidateRequerySuggested();
 }
开发者ID:mgrman,项目名称:SteamPaver,代码行数:7,代码来源:RelayCommad.cs

示例4: QueueTask

		protected internal override void QueueTask (Task t)
		{
			// Add to the shared work pool
			workQueue.TryAdd (t);
			// Wake up some worker if they were asleep
			PulseAll ();
		}
开发者ID:koush,项目名称:mono,代码行数:7,代码来源:Scheduler.cs

示例5: TaskDecoratorCoTask

        /// <summary>
        /// Initializes a new instance of the <see cref="TaskDecoratorCoTask"/> class.
        /// </summary>
        /// <param name="task">The task.</param>
        public TaskDecoratorCoTask(Task task)
        {
            if (task == null)
                throw new ArgumentNullException(nameof(task));

            _innerTask = task;
        }
开发者ID:belyansky,项目名称:Caliburn.Light,代码行数:11,代码来源:TaskDecoratorCoTask.cs

示例6: Start

        public void Start()
        {
            m_Listener.Start();
            m_Listen = true;

            m_AcceptTask = AcceptClients(m_Listener);
        }
开发者ID:diogos88,项目名称:LIB,代码行数:7,代码来源:TCPIPServer.cs

示例7: HandleResult

        private TodoItemViewModel[] HandleResult(Task<TodoItemViewModel[]> task)
        {
            if (task.Exception != null)
            {
                IsFaulted = true;
                if (IsTrying == false)
                {
                    StartTrying(5);
                    return new TodoItemViewModel[0];
                }
                return new TodoItemViewModel[0];
            }

            IsFaulted = false;
            IsTrying = false;
            var result = task.Result;
            SetupCommands(result);

            if (ItemsList.IsRefreshing)
            {
                try
                {
                    ItemsList.IsRefreshing = false;
                    ItemsList.EndRefresh();
                }
                catch (Exception ex)
                {
                }
            }

            return result;
        }
开发者ID:dianaromero8888,项目名称:crossPlatformDevelopment,代码行数:32,代码来源:ToDoList.xaml.cs

示例8: Load

        public void Load(BulkLoad load)
        {
            var tasks = new Task[load.Collections.Count];

            int i = 0;
            foreach (var pair in load.Collections)
            {
                var bulkCollection = pair.Value;
                var collectionName = pair.Key;
                var keys = bulkCollection.Documents.Keys;

                var bsonIdArray = new BsonArray(keys);

                var collection = _mongoDatabase.GetCollection(bulkCollection.CollectionType, collectionName);

                tasks[i] = Task.Factory.StartNew(() =>
                {
                    MongoCursor cursor = collection.FindAs(bulkCollection.CollectionType, Query.In("_id", bsonIdArray));

                    foreach (var doc in cursor)
                    {
                        var id = _metadata.GetDocumentId(doc);
                        bulkCollection.Documents[id] = doc;
                    }
                });
                i++;
            }
            Task.WaitAll(tasks);
        }
开发者ID:sergey-korol,项目名称:uniform,代码行数:29,代码来源:MongodbBulkLoader.cs

示例9: LoginScreen_IsVisibleChanged

 void LoginScreen_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
     if (this.IsVisible)
     {
         dbInitializingTask = Task.Factory.StartNew(() => DBResources.Instance.ReInstanceDbContext());
     }
 }
开发者ID:venkateshmani,项目名称:trinity,代码行数:7,代码来源:LoginScreen.xaml.cs

示例10: RunTestLoop

        private void RunTestLoop(int numberOfTasks, TaskScheduler[] schedulers)
        {
            var taskList = new List<Task>(numberOfTasks);

            for (int i = 0; i < numberOfTasks; i++)
            {
                int id = i; // capture
                Task t = new Task(() =>
                {
                    if (Verbose) output.WriteLine("Task: " + id);
                });

                if (schedulers == null || schedulers.Length == 0)
                {
                    t.Start();
                }
                else
                {
                    var scheduler = schedulers[i % schedulers.Length];
                    t.Start(scheduler);
                }

                taskList.Add(t);
            }

            Task.WaitAll(taskList.ToArray());
        }
开发者ID:PaulNorth,项目名称:orleans,代码行数:27,代码来源:QueuedTaskSchedulerTests_Set1.cs

示例11: CreateRemoteThread

        public Task CreateRemoteThread(MemoryWriter writer)
        {
            UIntPtr bytesWriten;
            Win32.WriteProcessMemory(processInfo.hProcess, writer.TargetStartAddress, writer.Buffer,
                (uint)writer.Size, out bytesWriten);

            //lastWin32Error = Marshal.GetLastWin32Error();

            Win32.FlushInstructionCache(processInfo.hProcess, writer.TargetStartAddress, new UIntPtr((uint)writer.Size));

            //lastWin32Error = Marshal.GetLastWin32Error();

            IntPtr hThread = Win32.CreateRemoteThread(processInfo.hProcess, IntPtr.Zero, 0, writer.CodeTargetStartAddress,
                IntPtr.Zero, 0, IntPtr.Zero);

            //lastWin32Error = Marshal.GetLastWin32Error();

            Task task = new Task(() =>
                {
                    Win32.WaitForSingleObject(hThread, Win32.INFINITE);

                    // Free the memory in the process that we allocated
                    Win32.VirtualFreeEx(processInfo.hProcess, writer.TargetStartAddress, 0, Win32.FreeType.Release);
                });
            task.Start();

            return task;
        }
开发者ID:pieterderycke,项目名称:Ninjector,代码行数:28,代码来源:InjectableProcess.cs

示例12: Execute

 public override async void Execute(Vertex start)
 {
     Initialize();
     algTask = Postorder(start);
     await algTask;
     base.Execute();
 }
开发者ID:daymonc,项目名称:Draw_Graph,代码行数:7,代码来源:PostOrder.cs

示例13: LogHttpResponse

 public static void LogHttpResponse(this DiagnosticListener @this, Task<HttpResponseMessage> responseTask, Guid loggingRequestId)
 {
     if (@this.IsEnabled(HttpHandlerLoggingStrings.ResponseWriteName))
     {
         ScheduleLogResponse(@this, responseTask, loggingRequestId);
     }
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:HttpHandlerDiagnosticListenerExtensions.cs

示例14: HandlePromptResponse

        private void HandlePromptResponse(
            Task<ShowChoicePromptResponse> responseTask)
        {
            if (responseTask.IsCompleted)
            {
                ShowChoicePromptResponse response = responseTask.Result;

                if (!response.PromptCancelled)
                {
                    this.consoleService.ReceivePromptResponse(
                        response.ChosenItem,
                        false);
                }
                else
                {
                    // Cancel the current prompt
                    this.consoleService.SendControlC();
                }
            }
            else
            {
                if (responseTask.IsFaulted)
                {
                    // Log the error
                    Logger.Write(
                        LogLevel.Error,
                        "ShowChoicePrompt request failed with error:\r\n{0}",
                        responseTask.Exception.ToString());
                }

                // Cancel the current prompt
                this.consoleService.SendControlC();
            }
        }
开发者ID:sunnyc7,项目名称:PowerShellEditorServices,代码行数:34,代码来源:PromptHandlers.cs

示例15: Process

		/// <summary>
		///		Añade una tarea a la cola y la ejecuta
		/// </summary>
		public void Process(AbstractProcessor objProcessor)
		{ Task objTask;
				
				// Añade el procesador a la cola
					Queue.Add(objProcessor);
				// Asigna los manejador de eventos
					objProcessor.ActionProcess += (objSender, objEventArgs) =>
																						{ if (ActionProcess != null)
																								ActionProcess(objSender, objEventArgs);
																						};
					objProcessor.Progress += (objSender, objEventArgs) =>
																			{ if (Progress != null)
																					Progress(objSender, objEventArgs);
																			};
					objProcessor.ProgressAction += (objSender, objEventArgs) =>
																						{ if (ProgressAction != null)
																								ProgressAction(objSender, objEventArgs);
																						};
					objProcessor.EndProcess += (objSender, objEventArgs) =>
																			{ TreatEndProcess(objSender as AbstractProcessor, objEventArgs);
																			};
				// Crea la tarea para la compilación en otro hilo
					objTask = new Task(() => objProcessor.Process());
				// Arranca la tarea de generación
					try
						{ objTask.Start();
						}
					catch (Exception objException)
						{ TreatEndProcess(objProcessor, 
															new EventArguments.EndProcessEventArgs("Error al lanzar el proceso" + Environment.NewLine + objException.Message,
																																		 new List<string> {objException.Message } ));
						}
		}
开发者ID:jbautistam,项目名称:CopySolutionsVisualStudio,代码行数:36,代码来源:TasksQueue.cs


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