-2
public class Car
    {
        public int TyresCount { get; set; }
        public int SpareTyreCount { get; set; }
        public int FrontTyres { get; set; }
        public int RearTyres { get; set; }
    }

    public class CarAssembly
    {

        public async Task<Car> Process(Car car)
        {
            car = await AssembleFrameAsync(car);
            //Option A
            SetTyreCount(car);
            //or Option B
            SetTireCountNonStatic(car);
            //or Option C
            await Task.Run(() => SetTyreCountAsync(car));
            car = await AssembleEngineAsync(car);
            return car;
        }

        public async Task<Car> AssembleFrame(Car car)
        {
            car = await httpclient.GetAsync("GetFrame");
            return car;
        }

        //Option A
        private static void SetTyreCount(Car car)
        {
            car.TyresCount = car.FrontTyres + car.RearTyres;
            car.SpareTyreCount = 1;
        }

        //Option B
        public void SetTyreCountNonStatic(Car car)
        {
            car.TyresCount = car.FrontTyres + car.RearTyres;
            car.SpareTyreCount = 1;
        }

        //Option C
        public void SetTyreCountAsync(Car car)
        {
            car.TyresCount = car.FrontTyres + car.RearTyres;
            car.SpareTyreCount = 1;
        }
        public async Task<Car> AssembleEngineAsync(Car car)
        {
            car = await httpclient.postAsync("assembleEngine");
            return car;
        }
    }

我有这个类CarAssembly有方法Process,它调用异步方法AssembleFrame然后它必须调用另一个方法到GetTyreCount这是获取计数的非常简单的方法,如上所述,上面有 3 个选项 OptionA、OptionB、OptionC这是调用这个简单的 CPU 绑定方法的正确方法。即使我所说的选项不正确,请提供您的想法什么是正确的方法。假设它是 WebAPI 中的类执行(无 UI)

4

1 回答 1

0

在 WebAPI 上,您应该使用选项 A 或 B。如果您不需要访问实例变量(例如记录器),请使用选项 A。如果您这样做,请使用选项 B。

作为一般规则,不要Task.Run在 ASP.NET 上使用。

于 2020-01-23T14:08:27.713 回答