本文整理汇总了C#中Task.ContinueWith方法的典型用法代码示例。如果您正苦于以下问题:C# Task.ContinueWith方法的具体用法?C# Task.ContinueWith怎么用?C# Task.ContinueWith使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.ContinueWith方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
public static void Main()
{
// Create Task, defer starting it, continue with another task
var t = new Task<Int32>(n => Sum((Int32)n), 1000);
t.Start();
// notice the use of the Result property
Task cwt = t.ContinueWith(task => Console.WriteLine("2. The sum is: " + task.Result));
Console.WriteLine("1. here");
cwt.Wait();
}
示例3: OnCompletedInternal
/// <summary>
/// Schedules the continuation onto the <see cref="Task"/> associated with this <see cref="TaskAwaiter"/>.
/// </summary>
/// <param name="task">The awaited task.</param>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="continuation"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext)
{
if (continuation == null)
{
throw new ArgumentNullException("continuation");
}
SynchronizationContext sc = continueOnCapturedContext ? SynchronizationContext.Current : null;
if (sc != null && sc.GetType() != typeof(SynchronizationContext))
{
task.ContinueWith(param0 =>
{
try
{
sc.Post(state => ((Action)state).Invoke(), continuation);
}
catch (Exception exception)
{
AsyncServices.ThrowAsync(exception, null);
}
});//, CancellationToken.None);, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return;
}
TaskScheduler taskScheduler = Task.DefaultScheduler;
if (task.IsCompleted)
{
//Task.Factory.StartNew(s => ((Action)s).Invoke(), continuation, CancellationToken.None, TaskCreationOptions.None, taskScheduler);
continuation();
return;
}
//if (taskScheduler != TaskScheduler.Default)
//{
// task.ContinueWith(_ => RunNoException(continuation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, taskScheduler);
// return;
//}
task.ContinueWith(param0 =>
{
if (IsValidLocationForInlining)
{
RunNoException(continuation);
return;
}
//Task.Factory.StartNew(s => RunNoException((Action)s), continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
continuation();
});//, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
示例4: OnAfter_GnomanEmpire_SaveGame
public static Task OnAfter_GnomanEmpire_SaveGame(Task result, GnomanEmpire self, bool fallen)
{
return result.ContinueWith((task) =>
{
GnomanEmpire.Instance.World.NotificationManager.AddNotification("Game saved within " + (DateTime.Now - SaveStart).TotalSeconds.ToString("0.00") + " sec", false);
});
}
示例5: ContinueTask
static public void ContinueTask(Task<object> task, object state)
{
// Will complete asynchronously. Schedule continuation to finish processing.
task.ContinueWith(new Action<Task<object>, object>(edgeAppCompletedOnCLRThread), state);
}
示例6: OpenRom
void OpenRom(string path)
{
this.progressbar1.Adjustment.Lower = 0;
this.progressbar1.Adjustment.Upper = 100;
//this.progressbar1.Adjustment.StepIncrement = 5;
this.progressbar1.Adjustment.Value = 0;
data.ProgressChanged += delegate(object s, System.ComponentModel.ProgressChangedEventArgs pArgs) { Application.Invoke (delegate { this.progressbar1.Adjustment.Value = pArgs.ProgressPercentage; }); };
this.statusbar1.Push (0, "Analyzing file " + System.IO.Path.GetFileName (path));
#if LOAD_SYNC
LoadRomTask (path);
//LoadRomDone (new Task((t) => Console.WriteLine ("LoadRomDone")));
#else
Task task = new Task (() => LoadRomTask (path));
// Exceptions must be handled in Task
task.ContinueWith (t => LoadRomDone (t));
task.Start ();
#endif
}
示例7: LoadFile
/// <summary>
/// Loads a new XNA asset file into the ModelViewerControl.
/// </summary>
public AssetType LoadFile(string fileName, XnaBuildProperties buildProperties)
{
if (!_loaded)
return AssetType.None;
// Unload any existing content.
graphicsDeviceControl.AssetRenderer = null;
AssetHandler assetHandler = _assetHandlers.GetAssetHandler(fileName);
assetHandler.ResetRenderer();
windowsFormsHost.Visibility = Visibility.Collapsed;
txtInfo.Text = "Loading...";
txtInfo.Visibility = Visibility.Visible;
// Load asynchronously.
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task<string> loadTask = new Task<string>(() =>
{
_contentManager.Unload();
// Tell the ContentBuilder what to build.
_contentBuilder.Clear();
_contentBuilder.SetReferences(buildProperties.ProjectReferences);
string assetName = fileName;
foreach (char c in Path.GetInvalidFileNameChars())
assetName = assetName.Replace(c.ToString(), string.Empty);
assetName = Path.GetFileNameWithoutExtension(assetName);
_contentBuilder.Add(fileName, assetName, buildProperties.Importer,
buildProperties.Processor ?? assetHandler.ProcessorName,
buildProperties.ProcessorParameters);
// Build this new model data.
string buildErrorInternal = _contentBuilder.Build();
if (string.IsNullOrEmpty(buildErrorInternal))
{
// If the build succeeded, use the ContentManager to
// load the temporary .xnb file that we just created.
assetHandler.LoadContent(assetName);
graphicsDeviceControl.AssetRenderer = assetHandler.Renderer;
}
return buildErrorInternal;
});
loadTask.ContinueWith(t =>
{
string buildError = t.Result;
if (!string.IsNullOrEmpty(buildError))
{
// If the build failed, display an error message.
txtInfo.Text = "Uh-oh. Something went wrong. Check the Output window for details.";
XBuilderWindowPane.WriteLine(buildError);
}
else
{
windowsFormsHost.Visibility = Visibility.Visible;
txtInfo.Visibility = Visibility.Hidden;
}
}, ui);
loadTask.Start();
return _assetHandlers.GetAssetType(fileName);
}
示例8: LogTaskException
/// <summary>
/// Logs exceptions thrown within task runtime.
/// </summary>
/// <param name="task">Task which exceptions should be logged</param>
private void LogTaskException(Task task)
{
task.ContinueWith(CMSThread.Wrap(
(Task t) =>
EventLogProvider.LogException("Score",
"SCORE_RECALCULATION",
t.Exception)
),
TaskContinuationOptions.OnlyOnFaulted);
}