本文整理汇总了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;
}
示例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();
}
示例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);
}
}
示例4: Promise
public Promise(Arguments args)
{
m_promiseTask = new Task<JSObject>(() =>
{
return Undefined;
});
}
示例5: AddOnChangeSetFailureTask
public void AddOnChangeSetFailureTask(Task onFailureTask)
{
lock (this)
{
_onFailureTasks.Add(onFailureTask);
}
}
示例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.
}
}
}
示例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]));
}
示例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;
}
}
示例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();
}
}
示例10: TryExecuteTaskInline
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (TryExecuteTaskInlineHandler != null)
TryExecuteTaskInlineHandler (task, taskWasPreviouslyQueued);
return base.TryExecuteTask (task);
}
示例11: Start
public void Start()
{
if (_running)
return;
_running = true;
_httpTask = Task.Run(() => RunTask(), _cts.Token);
}
示例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;
}
示例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();
}
}
示例14: QueueTask
protected override void QueueTask (Task task)
{
Interlocked.Increment (ref qc);
ThreadPool.QueueUserWorkItem (o => {
TryExecuteTask (task);
});
}
示例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();
}
}