當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。