如何:防止子任务附加到父任务
本文档演示如何阻止子任务附加到父任务。 在调用由第三方编写的也使用任务的组件时,阻止子任务附加到其父级是有用的。 例如,使用 TaskCreationOptions.AttachedToParent 选项创建 Task 或 Task<TResult> 对象的第三方组件,如果长时间运行或引发未经处理的异常,可能会导致代码中出现问题。
示例
下面的示例对使用默认选项的效果与阻止子任务附加到其父级的效果进行比较。 示例创建了一个 Task 对象,该对象可调入同时使用 Task 对象的第三方库。 第三方库使用 AttachedToParent 选项创建 Task 对象。 应用程序使用 TaskCreationOptions.DenyChildAttach 选项创建父任务。 该选项指示运行时移除子任务中的 AttachedToParent 规范。
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
// Defines functionality that is provided by a third-party.
// In a real-world scenario, this would likely be provided
// in a separate code file or assembly.
namespace Contoso
{
public class Widget
{
public Task Run()
{
// Create a long-running task that is attached to the
// parent in the task hierarchy.
return Task.Factory.StartNew(() =>
{
// Simulate a lengthy operation.
Thread.Sleep(5000);
}, TaskCreationOptions.AttachedToParent);
}
}
}
// Demonstrates how to prevent a child task from attaching to the parent.
class DenyChildAttach
{
static void RunWidget(Contoso.Widget widget,
TaskCreationOptions parentTaskOptions)
{
// Record the time required to run the parent
// and child tasks.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Console.WriteLine("Starting widget as a background task...");
// Run the widget task in the background.
Task<Task> runWidget = Task.Factory.StartNew(() =>
{
Task widgetTask = widget.Run();
// Perform other work while the task runs...
Thread.Sleep(1000);
return widgetTask;
}, parentTaskOptions);
// Wait for the parent task to finish.
Console.WriteLine("Waiting for parent task to finish...");
runWidget.Wait();
Console.WriteLine("Parent task has finished. Elapsed time is {0} ms.",
stopwatch.ElapsedMilliseconds);
// Perform more work...
Console.WriteLine("Performing more work on the main thread...");
Thread.Sleep(2000);
Console.WriteLine("Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds);
// Wait for the child task to finish.
Console.WriteLine("Waiting for child task to finish...");
runWidget.Result.Wait();
Console.WriteLine("Child task has finished. Elapsed time is {0} ms.",
stopwatch.ElapsedMilliseconds);
}
static void Main(string[] args)
{
Contoso.Widget w = new Contoso.Widget();
// Perform the same operation two times. The first time, the operation
// is performed by using the default task creation options. The second
// time, the operation is performed by using the DenyChildAttach option
// in the parent task.
Console.WriteLine("Demonstrating parent/child tasks with default options...");
RunWidget(w, TaskCreationOptions.None);
Console.WriteLine();
Console.WriteLine("Demonstrating parent/child tasks with the DenyChildAttach option...");
RunWidget(w, TaskCreationOptions.DenyChildAttach);
}
}
/* Sample output:
Demonstrating parent/child tasks with default options...
Starting widget as a background task...
Waiting for parent task to finish...
Parent task has finished. Elapsed time is 5014 ms.
Performing more work on the main thread...
Elapsed time is 7019 ms.
Waiting for child task to finish...
Child task has finished. Elapsed time is 7019 ms.
Demonstrating parent/child tasks with the DenyChildAttach option...
Starting widget as a background task...
Waiting for parent task to finish...
Parent task has finished. Elapsed time is 1007 ms.
Performing more work on the main thread...
Elapsed time is 3015 ms.
Waiting for child task to finish...
Child task has finished. Elapsed time is 5015 ms.
*/
Imports System.Diagnostics
Imports System.Threading
Imports System.Threading.Tasks
' Defines functionality that is provided by a third-party.
' In a real-world scenario, this would likely be provided
' in a separate code file or assembly.
Namespace Contoso
Public Class Widget
Public Function Run() As Task
' Create a long-running task that is attached to the
' parent in the task hierarchy.
Return Task.Factory.StartNew(Sub() Thread.Sleep(5000), TaskCreationOptions.AttachedToParent)
' Simulate a lengthy operation.
End Function
End Class
End Namespace
' Demonstrates how to prevent a child task from attaching to the parent.
Friend Class DenyChildAttach
Private Shared Sub RunWidget(ByVal widget As Contoso.Widget, ByVal parentTaskOptions As TaskCreationOptions)
' Record the time required to run the parent
' and child tasks.
Dim stopwatch As New Stopwatch()
stopwatch.Start()
Console.WriteLine("Starting widget as a background task...")
' Run the widget task in the background.
Dim runWidget As Task(Of Task) = Task.Factory.StartNew(Function()
' Perform other work while the task runs...
Dim widgetTask As Task = widget.Run()
Thread.Sleep(1000)
Return widgetTask
End Function, parentTaskOptions)
' Wait for the parent task to finish.
Console.WriteLine("Waiting for parent task to finish...")
runWidget.Wait()
Console.WriteLine("Parent task has finished. Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds)
' Perform more work...
Console.WriteLine("Performing more work on the main thread...")
Thread.Sleep(2000)
Console.WriteLine("Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds)
' Wait for the child task to finish.
Console.WriteLine("Waiting for child task to finish...")
runWidget.Result.Wait()
Console.WriteLine("Child task has finished. Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds)
End Sub
Shared Sub Main(ByVal args() As String)
Dim w As New Contoso.Widget()
' Perform the same operation two times. The first time, the operation
' is performed by using the default task creation options. The second
' time, the operation is performed by using the DenyChildAttach option
' in the parent task.
Console.WriteLine("Demonstrating parent/child tasks with default options...")
RunWidget(w, TaskCreationOptions.None)
Console.WriteLine()
Console.WriteLine("Demonstrating parent/child tasks with the DenyChildAttach option...")
RunWidget(w, TaskCreationOptions.DenyChildAttach)
End Sub
End Class
' Sample output:
'Demonstrating parent/child tasks with default options...
'Starting widget as a background task...
'Waiting for parent task to finish...
'Parent task has finished. Elapsed time is 5014 ms.
'Performing more work on the main thread...
'Elapsed time is 7019 ms.
'Waiting for child task to finish...
'Child task has finished. Elapsed time is 7019 ms.
'
'Demonstrating parent/child tasks with the DenyChildAttach option...
'Starting widget as a background task...
'Waiting for parent task to finish...
'Parent task has finished. Elapsed time is 1007 ms.
'Performing more work on the main thread...
'Elapsed time is 3015 ms.
'Waiting for child task to finish...
'Child task has finished. Elapsed time is 5015 ms.
'
因为父任务只有在所有子任务完成后才会完成,所以长时间运行的子任务会让整个应用程序执行得非常缓慢。 在此示例中,当应用程序使用默认选项创建父任务时,子任务必须在父任务完成之前完成。 当应用程序使用 TaskCreationOptions.DenyChildAttach 选项时,子任务未附加到父任务。 因此,应用程序可以在父任务完成之后且必须等待子任务完成之前执行其他工作。