c#-多线程-任务-返回值-简单类型

这段代码演示了在C#中如何使用Task类进行异步操作。创建了一个新的Task,将`Fun`方法作为任务执行,并传入参数a。在`Fun`方法内部,接收到对象o并转换为整数,返回其两倍值。任务执行完成后,通过Result属性获取返回值并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概要

var t1 = new Task<int>(Fun, a); 

int r = (int)t1.Result;

static int Fun(Object o) {
            int a = (int)o;
            return a*2;
        }

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.CompilerServices;

namespace ConsoleApp7
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("hello word");
            int a = 8;
            var t1 = new Task<int>(Fun, a);
            t1.Start();
            t1.Wait();
            int r = (int)t1.Result;
            Console.WriteLine(r);
            Console.ReadKey();
        }
        static int Fun(Object o) {
            int a = (int)o;
            return a*2;
        }

        
    }
}

运行结果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值