public static async Task CopyToAsync(
this Stream input, Stream output,
CancellationToken cancellationToken = default(CancellationToken))
{
byte[] buffer = new byte[0x1000]; // 4 KiB
while (true) {
cancellationToken.ThrowIfCancellationRequested();
int bytesRead = await input.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
cancellationToken.ThrowIfCancellationRequested();
await output.WriteAsync(buffer, 0, bytesRead);
}
}
public static /*async*/ Task CopyToAsync(
this Stream input, Stream output,
CancellationToken cancellationToken = default(CancellationToken))
{
return CopyToAsyncTasks(input, output, cancellationToken).ToTask();
}
private static IEnumerable<Task> CopyToAsyncTasks(
Stream input, Stream output,
CancellationToken cancellationToken)
{
byte[] buffer = new byte[0x1000]; // 4 KiB
while (true) {
cancellationToken.ThrowIfCancellationRequested();
var bytesReadTask = input.ReadAsync(buffer, 0, buffer.Length);
yield return bytesReadTask;
if (bytesReadTask.Result == 0) break;
cancellationToken.ThrowIfCancellationRequested();
yield return output.WriteAsync(buffer, 0, bytesReadTask.Result);
}
}
public /*async*/ void DoSomethingAsync() {
DoSomethingAsyncTasks().ToTask();
}
public /*async*/ Task DoSomethingAsync() {
return DoSomethingAsyncTasks().ToTask();
}
public /*async*/ Task<String> DoSomethingAsync() {
return DoSomethingAsyncTasks().ToTask<String>();
}
// C#5
public async Task<String> DoSomethingAsync() {
while (…) {
foreach (…) {
return "Result";
}
}
}
// C#4; DoSomethingAsync() is necessary but omitted here.
private IEnumerable<Task> DoSomethingAsyncTasks() {
while (…) {
foreach (…) {
yield return TaskEx.FromResult("Result");
goto END;
}
}
END: ;
}
public static Task<TResult> FromResult<TResult>(TResult resultValue) {
var completionSource = new TaskCompletionSource<TResult>();
completionSource.SetResult(resultValue);
return completionSource.Task;
}
private abstract class VoidResult { }
public static Task ToTask(this IEnumerable<Task> tasks) {
return ToTask<VoidResult>(tasks);
}
// BAD CODE !
public static Task<TResult> ToTask<TResult>(this IEnumerable<Task> tasks)
{
var tcs = new TaskCompletionSource<TResult>();
Task.Factory.StartNew(() => {
Task last = null;
try {
foreach (var task in tasks) {
last = task;
task.Wait();
}
// Set the result from the last task returned, unless no result is requested.
tcs.SetResult(
last == null || typeof(TResult) == typeof(VoidResult)
? default(TResult) : ((Task<TResult>) last).Result);
} catch (AggregateException aggrEx) {
// If task.Wait() threw an exception it will be wrapped in an Aggregate; unwrap it.
if (aggrEx.InnerExceptions.Count != 1) tcs.SetException(aggrEx);
else if (aggrEx.InnerException is OperationCanceledException) tcs.SetCanceled();
else tcs.SetException(aggrEx.InnerException);
} catch (OperationCanceledException cancEx) {
tcs.SetCanceled();
} catch (Exception ex) {
tcs.SetException(ex);
}
});
return tcs.Task;
}
// 很牛逼,但是我们还没有。
public static Task<TResult> ToTask<TResult>(this IEnumerable<Task> tasks)
{
var taskScheduler =
SynchronizationContext.Current == null
? TaskScheduler.Default : TaskScheduler.FromCurrentSynchronizationContext();
var tcs = new TaskCompletionSource<TResult>();
var taskEnumerator = tasks.GetEnumerator();
if (!taskEnumerator.MoveNext()) {
tcs.SetResult(default(TResult));
return tcs.Task;
}
taskEnumerator.Current.ContinueWith(
t => ToTaskDoOneStep(taskEnumerator, taskScheduler, tcs, t),
taskScheduler);
return tcs.Task;
}
private static void ToTaskDoOneStep<TResult>(
IEnumerator<Task> taskEnumerator, TaskScheduler taskScheduler,
TaskCompletionSource<TResult> tcs, Task completedTask)
{
var status = completedTask.Status;
if (status == TaskStatus.Canceled) {
tcs.SetCanceled();
} else if (status == TaskStatus.Faulted) {
tcs.SetException(completedTask.Exception);
} else if (!taskEnumerator.MoveNext()) {
// 设置最后任务返回的结果,直至无需结果为止。
tcs.SetResult(
typeof(TResult) == typeof(VoidResult)
? default(TResult) : ((Task<TResult>) completedTask).Result);
} else {
taskEnumerator.Current.ContinueWith(
t => ToTaskDoOneStep(taskEnumerator, taskScheduler, tcs, t),
taskScheduler);
}
}
public static Task<TResult> ToTask<TResult>(this IEnumerable<Task> tasks) {
var taskScheduler =
SynchronizationContext.Current == null
? TaskScheduler.Default : TaskScheduler.FromCurrentSynchronizationContext();
var taskEnumerator = tasks.GetEnumerator();
var completionSource = new TaskCompletionSource<TResult>();
// Clean up the enumerator when the task completes.
completionSource.Task.ContinueWith(t => taskEnumerator.Dispose(), taskScheduler);
ToTaskDoOneStep(taskEnumerator, taskScheduler, completionSource, null);
return completionSource.Task;
}
private static void ToTaskDoOneStep<TResult>(
IEnumerator<Task> taskEnumerator, TaskScheduler taskScheduler,
TaskCompletionSource<TResult> completionSource, Task completedTask)
{
// Check status of previous nested task (if any), and stop if Canceled or Faulted.
TaskStatus status;
if (completedTask == null) {
// This is the first task from the iterator; skip status check.
} else if ((status = completedTask.Status) == TaskStatus.Canceled) {
completionSource.SetCanceled();
return;
} else if (status == TaskStatus.Faulted) {
completionSource.SetException(completedTask.Exception);
return;
}
// Find the next Task in the iterator; handle cancellation and other exceptions.
Boolean haveMore;
try {
haveMore = taskEnumerator.MoveNext();
} catch (OperationCanceledException cancExc) {
completionSource.SetCanceled();
return;
} catch (Exception exc) {
completionSource.SetException(exc);
return;
}
if (!haveMore) {
// No more tasks; set the result (if any) from the last completed task (if any).
// We know it's not Canceled or Faulted because we checked at the start of this method.
if (typeof(TResult) == typeof(VoidResult)) { // No result
completionSource.SetResult(default(TResult));
} else if (!(completedTask is Task<TResult>)) { // Wrong result
completionSource.SetException(new InvalidOperationException(
"Asynchronous iterator " + taskEnumerator +
" requires a final result task of type " + typeof(Task<TResult>).FullName +
(completedTask == null ? ", but none was provided." :
"; the actual task type was " + completedTask.GetType().FullName)));
} else {
completionSource.SetResult(((Task<TResult>) completedTask).Result);
}
} else {
// When the nested task completes, continue by performing this function again.
taskEnumerator.Current.ContinueWith(
nextTask => ToTaskDoOneStep(taskEnumerator, taskScheduler, completionSource, nextTask),
taskScheduler);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有