在C#中,有多种方法可以用来监控异步任务。以下是一些建议:
try
{
Task task = Task.Run(() => YourAsyncMethod());
task.Wait();
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
{
Console.WriteLine("Error: " + ex.Message);
}
}
public async Task YourAsyncMethodAsync()
{
try
{
await Task.Run(() => YourAsyncMethod());
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
var tasks = new List<Task>
{
Task.Run(() => YourAsyncMethod1()),
Task.Run(() => YourAsyncMethod2())
};
try
{
await Task.WhenAll(tasks);
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
{
Console.WriteLine("Error: " + ex.Message);
}
}
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task task = Task.Run(() => YourAsyncMethod(token), token);
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Task canceled.");
}
else
{
task.Wait();
}
IProgress<int> progress = new Progress<int>(value => Console.WriteLine($"Progress: {value}%"));
Task task = Task.Run(() => YourAsyncMethodWithProgress(progress));
task.Wait();
public event EventHandler TaskCompleted;
public async Task YourAsyncMethod()
{
try
{
// 执行异步操作
}
finally
{
TaskCompleted?.Invoke(this, EventArgs.Empty);
}
}
// 在其他地方订阅事件
YourAsyncMethod += YourAsyncMethod_TaskCompleted;
private void YourAsyncMethod_TaskCompleted(object sender, EventArgs e)
{
Console.WriteLine("Task completed.");
}