本文整理汇总了C#中Task.RunSynchronously方法的典型用法代码示例。如果您正苦于以下问题:C# Task.RunSynchronously方法的具体用法?C# Task.RunSynchronously怎么用?C# Task.RunSynchronously使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.RunSynchronously方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RunWithSchedulerAsCurrent
/// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
{
var t = new Task(action);
t.RunSynchronously(scheduler);
t.GetAwaiter().GetResult();
}
示例2: TryExecuteTaskInline
/// <summary>Tries to execute the task synchronously on this scheduler.</summary>
/// <param name="task">The task to execute.</param>
/// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param>
/// <returns>true if the task could be executed; otherwise, false.</returns>
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_processingTaskOnCurrentThread.Value)
{
var t = new Task<bool>(state => TryExecuteTask((Task)state), task);
t.RunSynchronously(_interleave._parallelOptions.TaskScheduler);
return t.Result;
}
return false;
}
示例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();
//.........这里部分代码省略.........
示例5: RunSynchronizationContextTaskSchedulerTests
public static void RunSynchronizationContextTaskSchedulerTests()
{
// Remember the current SynchronizationContext, so that we can restore it
SynchronizationContext previousSC = SynchronizationContext.Current;
// Now make up a "real" SynchronizationContext abd install it
SimpleSynchronizationContext newSC = new SimpleSynchronizationContext();
SetSynchronizationContext(newSC);
// Create a scheduler based on the current SC
TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext();
//
// Launch a Task on scTS, make sure that it is processed in the expected fashion
//
bool sideEffect = false;
Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS);
Exception ex = null;
try
{
task.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(task.IsCompleted, "Expected task to have completed");
Assert.True(ex == null, "Did not expect exception on Wait");
Assert.True(sideEffect, "Task appears not to have run");
Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext");
//
// Run a Task synchronously on scTS, make sure that it completes
//
sideEffect = false;
Task syncTask = new Task(() => { sideEffect = true; });
ex = null;
try
{
syncTask.RunSynchronously(scTS);
}
catch (Exception e)
{
ex = e;
}
Assert.True(task.IsCompleted, "Expected task to have completed");
Assert.True(ex == null, "Did not expect exception on RunSynchronously");
Assert.True(sideEffect, "Task appears not to have run");
Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext");
//
// Miscellaneous things to test
//
Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1");
// restore original SC
SetSynchronizationContext(previousSC);
}
示例6: AllowsInlineExecutionAfterBeingQueued
public void AllowsInlineExecutionAfterBeingQueued()
{
var executions = 0;
var taskScheduler = new BlockingThreadPoolTaskScheduler();
var task = new Task(() => { executions++; }, CancellationToken.None, TaskCreationOptions.AttachedToParent);
task.RunSynchronously(taskScheduler);
Assert.Equal(1, executions);
Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
}
示例7: WaitForPreceedingTasksIfRequired
public void WaitForPreceedingTasksIfRequired()
{
var executionOrder = new List<Int32>();
var tasksQueued = new ManualResetEvent(false);
var taskScheduler = new PartitionedTaskScheduler();
Task.Factory.StartNew(() => { executionOrder.Add(0); tasksQueued.WaitOne(); Thread.Sleep(25); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
Task.Factory.StartNew(() => executionOrder.Add(1), CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
var synchronousTask = new Task(() => executionOrder.Add(2), CancellationToken.None, TaskCreationOptions.AttachedToParent);
tasksQueued.Set();
synchronousTask.RunSynchronously(taskScheduler);
Assert.Equal(3, executionOrder.Where((value, index) => value == index).Count());
}
示例8: WillDeadlockIfForceSynchronousExecutionsAcrossPartitions
public void WillDeadlockIfForceSynchronousExecutionsAcrossPartitions()
{
var tasksQueued = new ManualResetEvent(false);
var partition1Active = new ManualResetEvent(false);
var partition2Active = new ManualResetEvent(false);
var task1 = new Task(_ => { }, 1, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
var task2 = new Task(_ => { }, 2, CancellationToken.None, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
var taskScheduler = new PartitionedTaskScheduler(task => task.AsyncState, 2, 4);
var task3 = Task.Factory.StartNew(_ =>
{
tasksQueued.WaitOne();
partition1Active.Set();
partition2Active.WaitOne();
task1.RunSynchronously();
}, 2, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);
var task4 = Task.Factory.StartNew(_ =>
{
tasksQueued.WaitOne();
partition2Active.Set();
partition1Active.WaitOne();
task2.RunSynchronously();
}, 1, CancellationToken.None, TaskCreationOptions.LongRunning, taskScheduler);
tasksQueued.Set();
Assert.False(Task.WaitAll(new[] { task1, task2, task3, task4 }, 100));
}