在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.");
}