本文整理汇总了C#中System.Threading.Tasks.Task.ContinueWith方法的典型用法代码示例。如果您正苦于以下问题:C# Task.ContinueWith方法的具体用法?C# Task.ContinueWith怎么用?C# Task.ContinueWith使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.ContinueWith方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
// create the first generation task
Task firstGen = new Task(() => {
Console.WriteLine("Message from first generation task");
// comment out this line to stop the fault
throw new Exception();
});
// create the second generation task - only to run on exception
Task secondGen1 = firstGen.ContinueWith(antecedent => {
// write out a message with the antecedent exception
Console.WriteLine("Antecedent task faulted with type: {0}",
antecedent.Exception.GetType());
}, TaskContinuationOptions.OnlyOnFaulted);
// create the second generation task - only to run on no exception
Task secondGen2 = firstGen.ContinueWith(antecedent => {
Console.WriteLine("Antecedent task NOT faulted");
}, TaskContinuationOptions.NotOnFaulted);
// start the first generation task
firstGen.Start();
// wait for input before exiting
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}
示例2: Main
private static void Main(string[] args)
{
var task = new Task(() =>
{
Console.WriteLine("Task 1 rolls out");
throw new Exception();
});
task.ContinueWith(
task1 => Console.WriteLine("Task {0} nevermind of state, task result is {1}", task1.Id, task1.Status),
TaskContinuationOptions.None);
task.ContinueWith(
task1 => Console.WriteLine("Task {0} failed, task result is {1}", task1.Id, task1.Status),
TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(
task1 => Console.WriteLine("Task {0} failed executing continuation syncchronously, task result is {1}", task1.Id, task1.Status),
TaskContinuationOptions.ExecuteSynchronously);
task.ContinueWith(
task1 => Console.WriteLine("Task {0} runned outside the pool, task result is {1}", task1.Id, task1.Status),
TaskContinuationOptions.OnlyOnCanceled);
task.Start();
Console.ReadLine();
}
示例3: SetupSigninTaskContinuations
private void SetupSigninTaskContinuations(Task<LogOnInfo> signinTask,
TaskCompletionSource<UserViewModel> taskCompletionSource)
{
signinTask.ContinueWith(completedTask => CompleteSignin(completedTask.Result, taskCompletionSource),
TaskContinuationOptions.OnlyOnRanToCompletion);
signinTask.ContinueWith(failedTask => HandleSigninException(failedTask.Exception, taskCompletionSource),
TaskContinuationOptions.OnlyOnFaulted);
taskCompletionSource.Task.ContinueWith(
completedSignin => OnSigninComplete(completedSignin.Result, _logOnInfo.Rooms.Any()),
TaskContinuationOptions.OnlyOnRanToCompletion);
}
示例4: ProcessMessageAsync
public Task ProcessMessageAsync(string room, Message message)
{
var task = new Task<ChatMessageViewModel>(() =>
{
ChatMessageViewModel msgVm = CreateMessageViewModel(message);
return msgVm;
});
task.ContinueWith(completedTask => OnMessageProcessed(completedTask.Result, room),
TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(ProcessTaskExceptions, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
return task;
}
示例5: ToBegin
/// <summary>
///
/// </summary>
/// <param name="task"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
public static IAsyncResult ToBegin(Task task, AsyncCallback callback, object state)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
var tcs = new TaskCompletionSource<object>(state);
task.ContinueWith(t =>
{
if (task.IsFaulted)
{
if (task.Exception != null)
tcs.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(null);
//tcs.TrySetResult(RpcAction.GetTaskResult(t));
}
callback?.Invoke(tcs.Task);
}/*, TaskScheduler.Default*/);
return tcs.Task;
}
示例6: OnMikuniProtocol
private void OnMikuniProtocol()
{
status = DialogManager.ShowStatus(this, Database.GetText("Communicating", "System"));
Manager.LiveDataVector = Database.GetLiveData("QingQi");
for (int i = 0; i < Manager.LiveDataVector.Count; i++)
{
if ((Manager.LiveDataVector[i].ShortName == "TS")
|| (Manager.LiveDataVector[i].ShortName == "ERF")
|| (Manager.LiveDataVector[i].ShortName == "IS"))
{
Manager.LiveDataVector[i].Enabled = false;
}
}
Core.LiveDataVector vec = Manager.LiveDataVector;
vec.DeployEnabledIndex();
vec.DeployShowedIndex();
task = Task.Factory.StartNew(() =>
{
if (!Manager.Commbox.Close() || !Manager.Commbox.Open())
{
throw new IOException(Database.GetText("Open Commbox Fail", "System"));
}
Diag.MikuniOptions options = new Diag.MikuniOptions();
options.Parity = Diag.MikuniParity.Even;
Mikuni protocol = new Mikuni(Manager.Commbox, options);
protocol.StaticDataStream(vec);
});
task.ContinueWith((t) =>
{
ShowResult(t);
});
}
示例7: ParticipateUntil
public void ParticipateUntil (Task task)
{
ManualResetEventSlim evt = new ManualResetEventSlim (false);
task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously);
ParticipateUntil (evt, -1);
}
示例8: ConsultarCursosViewModel
public ConsultarCursosViewModel()
{
this.Periodos = new List<ConsultarPeriodosPeriodoDTO>();
var task = new Task(() =>
{
Status = "Consultando Períodos...";
var modelPeriodos = new ConsultarPeriodosModel();
var requestPeriodos = new ConsultarPeriodosRequest();
modelPeriodos.Execute(requestPeriodos);
if (modelPeriodos.Response.Status == ExecutionStatus.Success) this.Periodos = modelPeriodos.Response.Periodos;
else System.Windows.Forms.MessageBox.Show(string.Concat("Erro ao consultar professores:\n",modelPeriodos.ErrorMessage));
Periodos.Add(new ConsultarPeriodosPeriodoDTO() { Codigo = 0, Nome = "<Nenhum>" });
Status = "Consultando Cursos...";
var modelCursos = new ConsultarCursosModel();
var requestCursos = new ConsultarCursosRequest();
modelCursos.Execute(requestCursos);
if (modelCursos.Response.Status == ExecutionStatus.Success) this.Lista = modelCursos.Response.Cursos;
else System.Windows.Forms.MessageBox.Show(string.Concat("Erro ao consultar professores:\n",modelCursos.ErrorMessage));
});
task.ContinueWith(x =>
{
Status = "";
});
task.Start();
this.ActionCommand = new RelayCommand();
}
示例9: OnCreate
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
//create a new dialog
dialog = CustomProgressDialog.CreateDialog(this);
dialog.OnWindowFocusChanged(true);
Button btnGO = FindViewById<Button>(Resource.Id.go);
btnGO.Click += (s,e) =>
{
int result = 0;
//show the dialog
dialog.Show();
//do some things
Task task = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
result += i;
}
});
task.ContinueWith(t =>
{
Intent intent = new Intent(this, typeof(LastActivity));
intent.PutExtra("name", result.ToString());
StartActivity(intent);
});
task.Start();
};
}
示例10: AsyncResult
public AsyncResult(AsyncCallback callback, object state, Task task)
{
_state = state;
_task = task;
_completedSynchronously = _task.IsCompleted;
_task.ContinueWith(t => callback(this), TaskContinuationOptions.ExecuteSynchronously);
}
示例11: Track
public void Track(Task task, string inprogressText)
{
pictureBox.Image = Resources.spin;
label.Text = inprogressText;
label.ForeColor = DefaultForeColor;
toolTip.RemoveAll();
task
.ContinueWith(t => {
if (t.IsCanceled)
{
label.Text = "Cancelled";
label.ForeColor = Color.Peru;
pictureBox.Image = Resources.Ok;
}
else if (t.IsFaulted)
{
pictureBox.Image = Resources.Error;
label.Text = "ERROR";
label.ForeColor = Color.Red;
toolTip.SetToolTip(pictureBox, t.Exception.InnerException.Message);
toolTip.SetToolTip(label, t.Exception.InnerException.ToString());
}
else
{
pictureBox.Image = Resources.Ok;
label.Text = _rantoCompletionText;
}
}, TaskScheduler.FromCurrentSynchronizationContext())
;
}
示例12: LaunchThread
public static void LaunchThread()
{
Task<Int32[]> parent = new Task<int[]>(() =>
{
var results = new Int32[3];
// Use this factory configuration...
TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
// ... to create tasks
tf.StartNew(() => results[0] = 4);
tf.StartNew(() => results[1] = 5);
tf.StartNew(() => results[2] = 6);
return results;
});
parent.Start();
var finalTask = parent.ContinueWith(
parentTask =>
{
foreach (int i in parentTask.Result)
Console.WriteLine(i);
});
// Wait the task parent finished (and the child tasks finished)
finalTask.Wait();
// Result :
// 4
// 5
// 6
Console.ReadKey();
}
示例13: Main
public static void Main()
{
bool parentTaskFaulted = false;
Task task = new Task(() =>
{
throw new InvalidOperationException();
});
Task continuationTask = task.ContinueWith(
(antecedentTask) =>
{
parentTaskFaulted =
antecedentTask.IsFaulted;
}, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
continuationTask.Wait();
Trace.Assert(parentTaskFaulted);
if(!task.IsFaulted)
{
task.Wait();
}
else
{
task.Exception.Handle(eachException =>
{
Console.WriteLine(
"ERROR: {0}",
eachException.Message);
return true;
});
}
}
开发者ID:andrewdwalker,项目名称:EssentialCSharp,代码行数:31,代码来源:Listing18.08.ObservingUnhandledExceptionsWithContinueWith.cs
示例14: SaveSettings
void SaveSettings()
{
SetError();
if (MaxChatHistory.Value == null) MaxChatHistory.Value = 100;
var dataDirectory = TextBoxDataDirectory.Text;
var installOnBoot = CheckBoxInstallOnBoot.IsChecked ?? false;
var useLightChat = CheckBoxLightChat.IsChecked ?? false;
var useHardwareRendering = CheckBoxUseHardwareRendering.IsChecked ?? false;
var useTransparentWindows = CheckBoxUseWindowTransparency.IsChecked ?? false;
var maxChatHistory = MaxChatHistory.Value ?? 100;
var enableChatImages = CheckBoxEnableChatImages.IsChecked ?? false;
var enableChatGifs = CheckBoxEnableChatGifs.IsChecked ?? false;
var task = new Task(
() =>
this.SaveSettingsTask(
ref dataDirectory,
installOnBoot,
useLightChat,
useHardwareRendering,
useTransparentWindows,
maxChatHistory,
enableChatImages,
enableChatGifs));
task.ContinueWith((t) =>
{
Dispatcher
.Invoke(new Action(
() => this.SaveSettingsComplete(t)));
});
task.Start();
}
示例15: Main
static void Main(string[] args)
{
// create a first generation task
Task gen1 = new Task(() => {
// write out a message
Console.WriteLine("First generation task");
});
// create a second generation task
Task gen2 = gen1.ContinueWith(antecedent => {
// write out a message
Console.WriteLine("Second generation task - throws exception");
throw new Exception();
});
// create a third generation task
Task gen3 = gen2.ContinueWith(antecedent => {
// write out a message
Console.WriteLine("Third generation task");
});
// start the first gen task
gen1.Start();
// wait for the last task in the chain to complete
gen3.Wait();
// wait for input before exiting
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}