本文整理汇总了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);
}
示例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;
}
示例3: Execute
public async void Execute(object parameter)
{
asyncExecutingTask = this.asyncExecute();
await asyncExecutingTask;
asyncExecutingTask = null;
CommandManager.InvalidateRequerySuggested();
}
示例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 ();
}
示例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;
}
示例6: Start
public void Start()
{
m_Listener.Start();
m_Listen = true;
m_AcceptTask = AcceptClients(m_Listener);
}
示例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;
}
示例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);
}
示例9: LoginScreen_IsVisibleChanged
void LoginScreen_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.IsVisible)
{
dbInitializingTask = Task.Factory.StartNew(() => DBResources.Instance.ReInstanceDbContext());
}
}
示例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());
}
示例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;
}
示例12: Execute
public override async void Execute(Vertex start)
{
Initialize();
algTask = Postorder(start);
await algTask;
base.Execute();
}
示例13: LogHttpResponse
public static void LogHttpResponse(this DiagnosticListener @this, Task<HttpResponseMessage> responseTask, Guid loggingRequestId)
{
if (@this.IsEnabled(HttpHandlerLoggingStrings.ResponseWriteName))
{
ScheduleLogResponse(@this, responseTask, loggingRequestId);
}
}
示例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();
}
}
示例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 } ));
}
}