本文整理汇总了C#中Task.GetAwaiter方法的典型用法代码示例。如果您正苦于以下问题:C# Task.GetAwaiter方法的具体用法?C# Task.GetAwaiter怎么用?C# Task.GetAwaiter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.GetAwaiter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetResultNotCompleted
public void GetResultNotCompleted ()
{
TaskAwaiter awaiter;
var task = new Task (() => { });
awaiter = task.GetAwaiter ();
try {
awaiter.GetResult ();
Assert.Fail ();
} catch (InvalidOperationException) {
}
}
示例2: GetResultCanceled
public void GetResultCanceled ()
{
TaskAwaiter awaiter;
var token = new CancellationToken (true);
var task = new Task (() => { }, token);
awaiter = task.GetAwaiter ();
try {
awaiter.GetResult ();
Assert.Fail ();
} catch (TaskCanceledException) {
}
}
示例3: GetResultFaulted
public void GetResultFaulted ()
{
TaskAwaiter awaiter;
var task = new Task (() => { throw new ApplicationException (); });
awaiter = task.GetAwaiter ();
task.RunSynchronously (TaskScheduler.Current);
Assert.IsTrue (awaiter.IsCompleted);
try {
awaiter.GetResult ();
Assert.Fail ();
} catch (ApplicationException) {
}
}
示例4: WaitOnMainThread
private static bool WaitOnMainThread(Task task, CancellationToken cancellationToken, int ms) {
var frame = new DispatcherFrame();
var resultTask = Task.Run(() => {
try {
return task.Wait(ms, cancellationToken);
} catch(Exception) {
return true;
} finally {
frame.Continue = false;
}
});
Dispatcher.PushFrame(frame);
if (!resultTask.GetAwaiter().GetResult()) {
return false;
}
task.GetAwaiter().GetResult();
return true;
}
示例5: OperationCanceledException_PropagatesThroughCanceledTask
public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
{
var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
Assert.Same(expected, caught);
}
示例6: OnSendAsync
private void OnSendAsync(Task antecedent)
{
Contract.Assert(antecedent != null, "Argument 'antecedent' cannot be NULL.");
this.CancelSendTimer();
try
{
antecedent.GetAwaiter().GetResult();
}
catch (Exception exception)
{
if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
{
SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
_asyncWriteException = ConvertSendException(socketException, TimeSpan.MaxValue);
}
else
{
if (Fx.IsFatal(exception))
{
throw;
}
_asyncWriteException = exception;
}
}
this.FinishWrite();
}
示例7: FlushWriteImmediate
private static Task FlushWriteImmediate(Task antecedant, object state)
{
antecedant.GetAwaiter().GetResult();
RTSocketConnection thisPtr = (RTSocketConnection)state;
return thisPtr._outputStream.FlushAsync(thisPtr._sendCts.Token);
}
示例8: ContextTest
public void ContextTest ()
{
TaskAwaiter awaiter;
var task = new Task (() => { throw new ApplicationException (); });
awaiter = task.GetAwaiter ();
task.RunSynchronously (TaskScheduler.Current);
Assert.IsTrue (awaiter.IsCompleted);
try {
awaiter.GetResult ();
Assert.Fail ();
} catch (ApplicationException) {
}
var context = new MyContext ();
var old = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext (context);
try {
var t = new Task (delegate { });
var a = t.GetAwaiter ();
a.OnCompleted (delegate { });
t.Start ();
Assert.IsTrue (t.Wait (5000), "#1");
} finally {
SynchronizationContext.SetSynchronizationContext (old);
}
Assert.IsTrue (context.mre.WaitOne (5000), "#2");
Assert.AreEqual (1, context.PostCounter, "#3");
}
示例9: CompleteTask
private static void CompleteTask(Task t)
{
//observe the result on the main thread, which will propegate execeptions
sCallbacks.Add(new Tuple<SendOrPostCallback, object>(_ => t.GetAwaiter().GetResult(), null));
CompleteTask();
}
示例10: loadRowsAsync
private void loadRowsAsync()
{
subscribeToUserConfigCache(false);
changeReloadButtonStatus(enabled_: false);
ProductList.RegisterMongoClasses();
var userConfigsTask = new Task(() =>
{
setStatus("Loading user lists...");
UserListCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();
});
var listTask = new Task<IList<SwapsSummaryRow>>(() =>
{
subscribeToUserConfigCache();
ProductList.RegisterMongoClasses();
setStatus("Pulling DFs from server...");
DFsCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();
setStatus("Loading tenor dates...");
TenorDatesCache.Instance().RefreshFromServerIfLocalCacheEmpty().Wait();
return
UserListCache.Instance()
.InnerList.Select(item => new {Config = item, Impl = item.CreateInstrument()})
.Select(i => new SwapsSummaryRow(i.Impl, i.Config))
.ToList();
});
userConfigsTask.GetAwaiter().OnCompleted(() =>
{
profileManageDisplay1.UserListSelected -= handleUserListSelected;
profileManageDisplay1.Create();
m_filter.ProfileName = profileManageDisplay1.SelectedProfile;
profileManageDisplay1.UserListSelected += handleUserListSelected;
listTask.Start();
});
listTask.GetAwaiter().OnCompleted(() =>
{
setStatus("Loading structures...");
var list = listTask.Result;
ThreadStart finishLoadingGUI = () =>
{
setStatus(string.Empty);
m_originalList = list;
rebuildWorkingSet();
m_grid.Create(m_workingSet);
kickOffLiveSubscriptions();
changeReloadButtonStatus(enabled_: true);
};
if (list.Count == 0)
{
finishLoadingGUI();
}
else
{
try
{
Task first = null, prev = null;
foreach (var item in list)
{
var task = new Task(() =>
{
item.GetRawStat(StatCols.Values); // kick off stat retrieval
item.UpdateCentrallyControlledStats();
//item.SubscribeToLive();
});
if (first == null)
first = task;
if (prev == null)
prev = task;
else
{
prev.GetAwaiter().OnCompleted(() =>
{
setStatus(string.Format("Retrieving stats for {0}.{1}", item.Instrument.CurveName, item.Instrument.Description));
task.Start();
});
prev = task;
}
}
// last one -
if (prev != null)
{
prev.GetAwaiter().OnCompleted(() =>
//.........这里部分代码省略.........
示例11: ReadBuffer
// This is the async callback function. Only one thread could/should call this.
private void ReadBuffer(Task<int> t)
{
int byteLen;
try
{
byteLen = t.GetAwaiter().GetResult();
}
catch (IOException)
{
// We should ideally consume errors from operations getting cancelled
// so that we don't crash the unsuspecting parent with an unhandled exc.
// This seems to come in 2 forms of exceptions (depending on platform and scenario),
// namely OperationCanceledException and IOException (for errorcode that we don't
// map explicitly).
byteLen = 0; // Treat this as EOF
}
catch (OperationCanceledException)
{
// We should consume any OperationCanceledException from child read here
// so that we don't crash the parent with an unhandled exc
byteLen = 0; // Treat this as EOF
}
if (byteLen == 0)
{
// We're at EOF, we won't call this function again from here on.
lock (_messageQueue)
{
if (_sb.Length != 0)
{
_messageQueue.Enqueue(_sb.ToString());
_sb.Length = 0;
}
_messageQueue.Enqueue(null);
}
try
{
// UserCallback could throw, we should still set the eofEvent
FlushMessageQueue();
}
finally
{
_eofEvent.Set();
}
}
else
{
int charLen = _decoder.GetChars(_byteBuffer, 0, byteLen, _charBuffer, 0);
_sb.Append(_charBuffer, 0, charLen);
GetLinesFromStringBuilder();
_stream.ReadAsync(_byteBuffer, 0, _byteBuffer.Length).ContinueWith(ReadBuffer);
}
}
示例12: PumpTill
internal override void PumpTill(Task task)
{
task.GetAwaiter().GetResult();
}
示例13: ValidateFaultedTask
private static bool ValidateFaultedTask(Task t)
{
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
bool localPassed = t.IsFaulted;
try
{
t.GetAwaiter().GetResult();
Debug.WriteLine(" > FAILURE. Faulted task's GetResult should have thrown.");
}
catch (Exception e) { localPassed &= ValidateException(e); }
return localPassed;
}
示例14: ContextTest
public void ContextTest ()
{
var context = new MyContext ();
var old = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext (context);
try {
var t = new Task (delegate { });
var a = t.GetAwaiter ();
a.OnCompleted (delegate { });
t.Start ();
Assert.IsTrue (t.Wait (1000), "#1");
} finally {
SynchronizationContext.SetSynchronizationContext (old);
}
Assert.AreEqual (1, context.PostCounter, "#2");
}
示例15: 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();
}