本文整理汇总了C#中System.Threading.Tasks.Task.RunSynchronously方法的典型用法代码示例。如果您正苦于以下问题:C# Task.RunSynchronously方法的具体用法?C# Task.RunSynchronously怎么用?C# Task.RunSynchronously使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.RunSynchronously方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
protected virtual void Run(Action<Func<bool>> runAction, bool async) {
// New task, increment id;
Interlocked.Increment(ref _taskId);
// Do not run multiple tasks. According to http://msdn.microsoft.com/en-us/library/dd270681.aspx
// task can only be disposed if it is RanToCompletion, Faulted, or Canceled.
// If task is not in one of those states, we queue it for disposal later.
// Note that task may actually still be running since it may not be able to
// cancel immediately. The important part is that we don't care about its results.
// This means that task we no longer care about can still signal completion and
// we should ignore it. We use taskId member to determine if task calling is
// the current task.
SignalTaskBegins();
_task = new Task((taskId) => {
try {
Func<bool> isCancelledCallback = () => { return IsCancellationRequested() || (TaskId != (long)taskId); };
runAction(isCancelledCallback);
} catch (Exception) { } finally { }
}, TaskId);
if (!async) {
_task.RunSynchronously();
DisposeTask();
} else {
_task.Start();
}
}
示例2: QueueTask
public void QueueTask(ITask task)
{
Task newTask = new Task(delegate () {
task.Execute();
});
newTask.RunSynchronously(this);
}
示例3: Run
public override void Run()
{
/*
_storeName = "single-thread-test";
if (_client.DoesStoreExist(_storeName))
{
_client.DeleteStore(_storeName);
}
_client.CreateStore(_storeName);
*/
var importTask = new Task(AddData);
for (int i = 0; i < 5; i++)
{
var queryTask = new Task(QueryData);
_queryTasks.Add(queryTask);
queryTask.Start();
}
importTask.RunSynchronously();
_endQueries = true;
Task.WaitAll(_queryTasks.ToArray());
if (File.Exists("querytimes.txt")) File.Delete("querytimes.txt");
using(var writer= new StreamWriter(File.OpenWrite("querytimes.txt")))
{
foreach(var qt in _queryTimes)
{
writer.WriteLine("{0},{1}", qt.Item1, qt.Item2);
}
writer.Close();
}
Console.WriteLine("Ran {0} queries during import. Query times written to querytimes.txt", _queryTimes.Count);
}
示例4: ShouldNotFreakOutWhenItCantLookUpAWord
public void ShouldNotFreakOutWhenItCantLookUpAWord()
{
//Arrange
var task = new Task<HttpResponseMessage>(() => new HttpResponseMessage
{
Content = new StringContent("{" +
" \"word\": \"stub\"," +
" \"definition\": \"Sorry, boet, this_word_is_almost_guaranteed_not_to_exist_if_only_I_had_mocks_and_stuff_reach is not defined in this dictionary.\"" +
"}")
});
task.RunSynchronously();
_transport.Setup(x => x.GetAsync(It.IsAny<string>()))
.Returns(task);
var service = new RailsLookupService(()=>_transport.Object);
var word = "this_word_is_almost_guaranteed_not_to_exist_if_only_I_had_mocks_and_stuff_reach";
//Act
Task<string> lookup = service.Lookup(word);
var result = lookup;
//Assert
Assert.AreEqual(string.Format(NotFoundText, word), result.Result);
}
示例5: TryExecuteTaskInline
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (task.Status != TaskStatus.Created)
return false;
task.RunSynchronously (scheduler.target);
return true;
}
示例6: RunSynchronously
//-----------------------------------------------------------------------------------
// Executes the task synchronously (on the current thread).
//
internal Task RunSynchronously(TaskScheduler taskScheduler)
{
Debug.Assert(taskScheduler == TaskScheduler.Default, "PLINQ queries can currently execute only on the default scheduler.");
TraceHelpers.TraceInfo("[timing]: {0}: Running work synchronously", DateTime.Now.Ticks, _taskIndex);
Task task = new Task(s_runTaskSynchronouslyDelegate, this, TaskCreationOptions.AttachedToParent);
task.RunSynchronously(taskScheduler);
return task;
}
示例7: Configure
protected override void Configure()
{
container = new PhoneContainer();
#if DEBUG
LogManager.GetLog = type => new DebugLogger(type);
#endif
container.RegisterPhoneServices(RootFrame);
var initTasks = new Task(() => PerformAsyncInitializationsAsync());
initTasks.RunSynchronously();
container.RegisterPerRequest(typeof(IConfigurationService), null, typeof(DefaultConfigurationService));
container.RegisterPerRequest(typeof(IDataService), null, typeof(DefaultDataService));
container.RegisterPerRequest(typeof(ILocationService), null, typeof(DefaultLocationService));
container.RegisterPerRequest(typeof(IUIService), null, typeof(DefaultUIService));
// container.RegisterPerRequest(typeof(IEchtzeitdatenService), null, typeof(CreateCampEchtzeitdatenService));
container.RegisterPerRequest(typeof(IEchtzeitdatenService), null, typeof(OgdEchtzeitdatenService));
container.RegisterPerRequest(typeof(IRoutingService), null, typeof(OgdRoutingService));
container.PerRequest<MainPageViewModel>();
container.PerRequest<MenuViewModel>();
container.PerRequest<TrafficInfoViewModel>();
container.PerRequest<FavoritesViewModel>();
container.PerRequest<StationsPivotPageViewModel>();
container.PerRequest<StationsListViewModel>();
container.PerRequest<StationsSearchViewModel>();
container.PerRequest<NearbyStationsViewModel>();
container.PerRequest<LinesPivotPageViewModel>();
container.PerRequest<MetroViewModel>();
container.PerRequest<TramViewModel>();
container.PerRequest<BusViewModel>();
container.PerRequest<NightBusViewModel>();
container.PerRequest<LineInfoPageViewModel>();
container.PerRequest<MapNearbyStationsPageViewModel>();
container.PerRequest<StationInfoPivotPageViewModel>();
container.PerRequest<DepartureViewModel>();
container.PerRequest<RoutingPageViewModel>();
container.PerRequest<NewRouteViewModel>();
container.PerRequest<StationSelectorViewModel>();
container.PerRequest<RouteHistoryViewModel>();
container.PerRequest<TripsViewModel>();
container.PerRequest<SettingsPageViewModel>();
container.PerRequest<AboutPageViewModel>();
AddCustomConventions();
}
示例8: ChangeInterval
/// <summary>
/// Function to set timer time to specific time.
/// </summary>
/// <param name="timer">Object of type Timer</param>
/// <param name="dueTime">Timer due time</param>
/// <param name="period">Timer due period</param>
/// <returns>True or false</returns>
public static bool ChangeInterval(this Timer timer, int dueTime, int period)
{
using (var task = new Task(() => timer.Change(dueTime, period)))
{
task.RunSynchronously();
LogException(task.Exception);
return !task.IsFaulted;
}
}
示例9: TryExecuteTaskInlineExecutesTaskSynchronously
public void TryExecuteTaskInlineExecutesTaskSynchronously()
{
int taskThreadId = 0;
var task = new Task(() => { taskThreadId = Thread.CurrentThread.ManagedThreadId; });
task.RunSynchronously(new CurrentThreadTaskScheduler());
Assert.Equal(Thread.CurrentThread.ManagedThreadId, taskThreadId);
}
示例10: TryExecuteTaskInline
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (task == null)
{
throw new ArgumentNullException("task");
}
task.RunSynchronously();
return true;
}
示例11: RunSynchronously
public void RunSynchronously ()
{
var aTask = new Task (() => {
/* Do Something */
IsSet = true;
Thread.Sleep (1);
});
aTask.RunSynchronously ();
}
示例12: Lookup
public Task<string> Lookup(string word)
{
var output = "this word you speak of I have not found";
if (_dictionary.ContainsKey(word))
{
output = _dictionary[word];
}
var task = new Task<string>(() => output);
task.RunSynchronously();
return task;
}
示例13: BasicRunSynchronouslyTest
public void BasicRunSynchronouslyTest ()
{
bool ran = false;
var t = new Task (() => ran = true);
t.RunSynchronously ();
Assert.IsTrue (t.IsCompleted);
Assert.IsFalse (t.IsFaulted);
Assert.IsFalse (t.IsCanceled);
Assert.IsTrue (ran);
}
示例14: Case1
static void Case1()
{
Task task = new Task(() =>
{
Console.WriteLine("i am a task. thread id:{0}", Thread.CurrentThread.ManagedThreadId);
});
//task.Start();//异步执行
task.RunSynchronously();//同步执行
Console.WriteLine("main thread id:{0}", Thread.CurrentThread.ManagedThreadId);
}
示例15: Synchronize_GetVersionsAndGetReturnDuplicateEntries_RemovesDuplicates
public async Task Synchronize_GetVersionsAndGetReturnDuplicateEntries_RemovesDuplicates ()
{
var builder = new SynchronizerBuilder();
builder.AtypeIdComparer = StringComparer.InvariantCultureIgnoreCase;
builder.AtypeRepository
.Expect (r => r.GetVersions())
.IgnoreArguments()
.Return (
Task.FromResult<IReadOnlyList<EntityIdWithVersion<string, string>>> (
new[] { EntityIdWithVersion.Create ("A1", "v1"), EntityIdWithVersion.Create ("a1", "v3") }));
builder.BtypeRepository
.Expect (r => r.GetVersions())
.IgnoreArguments()
.Return (
Task.FromResult<IReadOnlyList<EntityIdWithVersion<string, string>>> (
new[] { EntityIdWithVersion.Create ("b1", "v2") }));
Task<IReadOnlyList<EntityWithVersion<string, string>>> aTypeLoadTask = new Task<IReadOnlyList<EntityWithVersion<string, string>>> (
() => new List<EntityWithVersion<string, string>> { EntityWithVersion.Create ("A1", "AAAA"), EntityWithVersion.Create ("a1", "____") });
aTypeLoadTask.RunSynchronously();
builder.AtypeRepository
.Expect (r => r.Get (Arg<ICollection<string>>.Matches (c => c.Count == 1 && c.First() == "A1")))
.Return (aTypeLoadTask);
Task<IReadOnlyList<EntityWithVersion<string, string>>> bTypeLoadTask = new Task<IReadOnlyList<EntityWithVersion<string, string>>> (
() => new List<EntityWithVersion<string, string>> { EntityWithVersion.Create ("b1", "BBBB"), });
bTypeLoadTask.RunSynchronously();
builder.BtypeRepository
.Expect (r => r.Get (Arg<ICollection<string>>.Matches (c => c.Count == 1 && c.First() == "b1")))
.Return (bTypeLoadTask);
var knownData = new EntityRelationData<string, string, string, string> ("A1", "v1", "b1", "v2");
builder.InitialEntityMatcher
.Expect (m => m.FindMatchingEntities (null, null, null, null, null))
.IgnoreArguments()
.Return (new List<IEntityRelationData<string, string, string, string>> { knownData });
builder.InitialSyncStateCreationStrategy
.Expect (s => s.CreateFor_Unchanged_Unchanged (knownData))
.Return (new DoNothing<string, string, string, string, string, string> (knownData));
var synchronizer = builder.Build();
await synchronizer.Synchronize();
builder.EntityRelationDataAccess.AssertWasCalled (
c => c.SaveEntityRelationData (Arg<List<IEntityRelationData<string, string, string, string>>>.Matches (l => l.Count == 1 && l[0] == knownData)));
}