怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

Task C#后台任务

C# 创建一个没有返回值的任务

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建并启动一个没有返回值的任务
Task task1 = Task.Run(() =>
{
Console.WriteLine("Task 1 is running on a thread pool thread.");
Thread.Sleep(2000); // Simulate work with Sleep
Console.WriteLine("Task 1 has completed.");
});
// 创建并启动一个有返回值的任务
Task<int> task2 = Task.Run(() =>
{
Console.WriteLine("Task 2 is performing some calculations...");
Thread.Sleep(1500); // Simulate work with Sleep
return 42; // Return the result of the calculation
});
// Wait for both tasks to complete and handle their results.
System.Console.WriteLine("Main thread is waiting for Task 1 to complete.");
await Task.WhenAll(task1, task2);
// Get the result from task2.
int result = await task2;
Console.WriteLine($"The result from Task 2 is: {result}");
}
}

C# 创建一个可以取消的任务

class Program
{
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
try
{
Task task3 = Task.Run(
() =>
{
while (true)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested, task 3 is stopping.");
break;
}
Console.WriteLine("Task 3 is working...");
Thread.Sleep(500);
}
},
cts.Token
);
// Let task3 run for a short time before cancelling it.
await Task.Delay(2000);
// 只要cts.Cancel()就会一直运行,👇👇👇👇👇👇👇👇👇👇👇👇
cts.Cancel(); // Request cancellation after 2 seconds.
// Wait for task3 to recognize the cancellation request and stop.
await task3;
}
catch (OperationCanceledException ex)
{
Console.WriteLine($"Task was cancelled: {ex.Message}");
}
}
}
posted on   超级无敌美少男战士  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2024-01-23 dotnet注册服务 secs4net secs
2024-01-23 dotnet 扩展Service方法 secs4net
2024-01-23 csharp 扩展方法
2022-01-23 tampermonkey 油猴脚本 博客园美化
点击右上角即可分享
微信分享提示