运行
namespace Example
{
class MyApplication
{
public static void Main()
{
Task t = Task.Run(() =>
{
for (int i = 0; i < 100; i++)
Console.WriteLine(i);
});
t.Wait();
}
}
}
返回一个值
namespace Example
{
class MyApplication
{
public static void Main()
{
Task<int> t = Task.Run(() =>
{
return 40;
});
Console.WriteLine(t.Result); //输出40
}
}
}
ContinueWith
namespace Example
{
class MyApplication
{
public static void Main()
{
Task<int> t = Task.Run(() =>
{
return 40;
});
t.ContinueWith((i) =>
{
Console.WriteLine("Canceled");
}, TaskContinuationOptions.OnlyOnCanceled);
t.ContinueWith((i) =>
{
Console.WriteLine("Faulted");
}, TaskContinuationOptions.OnlyOnFaulted);
var completedtask=t.ContinueWith((i) =>
{
Console.WriteLine("Completed");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
completedtask.Wait();
Console.WriteLine(t.Result);
}
}
}
父线程将会在子线程结束后结束
namespace Example
{
class MyApplication
{
public static void Main()
{
Task<Int32[]> parent = Task.Run(() =>
{
var result = new Int32[3];
new Task(() => result[0] = 0, TaskCreationOptions.AttachedToParent).Start();
new Task(() => result[1] = 1, TaskCreationOptions.AttachedToParent).Start();
new Task(() => result[2] = 2, TaskCreationOptions.AttachedToParent).Start();
return result;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
{
Console.WriteLine(i);
}
});
finalTask.Wait();
}
}
}
使用TaskFactory
namespace Example
{
class MyApplication
{
public static void Main()
{
Task<Int32[]> parent = Task.Run(() =>
{
var result = new Int32[3];
TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
tf.StartNew(() => result[0] = 0);
tf.StartNew(() => result[1] = 1);
tf.StartNew(() => result[2] = 2);
return result;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
{
Console.WriteLine(i);
}
});
finalTask.Wait();
}
}
}
Task.WaitAlL 等待提供的所有 Task 对象完成执行过程。
Task.WaitAny 等待提供的任何 Task 对象完成执行过程。