本文整理汇总了C#中Task.Wait方法的典型用法代码示例。如果您正苦于以下问题:C# Task.Wait方法的具体用法?C# Task.Wait怎么用?C# Task.Wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.Wait方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Beginning
public static void Beginning()
{
// аналоги вызова метода в потоке из ThreadPool
// Task даёт бОльшую гибкость
ThreadPool.QueueUserWorkItem(o => LongRunningMethod());
new Task(LongRunningMethod).Start();
Task.Run(() => LongRunningMethod());
Task<int> t = new Task<int>(LongRunningMethodWithResult);
t.Start(); // запуск задания
// блокировка вызвавшего потока до завершения задания
// однако, если задание ещё не выполняется, вызвавший поток может
// быть назначен исполнителем задания и он не блокируется
t.Wait();
// получение результата выполнения задания
// свойство Result вызывает метод Wait()
int result = t.Result;
// выполнение нового задания по завершении предыдущего
Task newTask = t.ContinueWith(m => Console.WriteLine(t.Result));
// блокировка вызвавшего потока, пока не завершатся
// все / хотя бы один метод из параметров
Task.WaitAll(t);
Task.WaitAny(t);
}
示例2: Main
static void Main(string[] args) {
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Task t = new Task(() =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
});
t.Start();
t.Wait();
Console.ReadLine();
}
示例3: Send
/// <summary>Dispatches a synchronous message to the synchronization context.</summary>
/// <param name="d">The System.Threading.SendOrPostCallback delegate to call.</param>
/// <param name="state">The object passed to the delegate.</param>
public override void Send(SendOrPostCallback d, object state)
{
Task t = new Task(() => d(state));
t.RunSynchronously(_scheduler);
t.Wait();
}
示例4: RunBuggySchedulerTests
public static void RunBuggySchedulerTests()
{
Debug.WriteLine("* RunBuggySchedulerTests()");
BuggyTaskScheduler bts = new BuggyTaskScheduler();
Task t1 = new Task(delegate { });
Task t2 = new Task(delegate { });
//
// Test Task.Start(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.Start(buggy scheduler)");
try
{
t1.Start(bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException)
{
}
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
if (t1.Status != TaskStatus.Faulted)
{
Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
}
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
t1.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait()."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
//
// Test Task.RunSynchronously(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.RunSynchronously(buggy scheduler)");
try
{
t2.RunSynchronously(bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException) { }
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
if (t2.Status != TaskStatus.Faulted)
{
Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
}
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
t2.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait()."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
//
// Test StartNew(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.Factory.StartNew(buggy scheduler)");
try
{
Task t3 = Task.Factory.StartNew(delegate { }, CancellationToken.None, TaskCreationOptions.None, bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException) { }
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
//
// Test continuations
//
Debug.WriteLine(" -- testing Task.ContinueWith(buggy scheduler)");
Task completedTask = Task.Factory.StartNew(delegate { });
completedTask.Wait();
//.........这里部分代码省略.........