异步控制器的任务支持,关于如何实现“sportsservice”的类。通过TAP [英] Task support for asynchronous controllers about how to implement the classs for "sportsservice" by TAP

查看:86
本文介绍了异步控制器的任务支持,关于如何实现“sportsservice”的类。通过TAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过检查结果,我知道,如果服务调用是异步(并行),总响应时间将略微超过8000毫秒,

现在,我的问题是类对于WeatherService如何实现,1认为,我也使用EAP来解决问题,但现在TAP是.NET Framework中异步编程的推荐方法,我如何通过TAP实现

blow是我的源代码



1:同步情况

关于控制器

By Checking the result,i know , if the service calls are made asynchronously (in parallel), the total response time will be slightly more than 8000 millisecond,
NOW ,MY QUESTION IS the Class for "WeatherService" How to implement ,1 think ,I also use the EAP to solve the problem,but now TAP is the recommended approach to asynchronous programming in the .NET Framework,how I can achieve by the TAP
blow is my source code

1:Synchronous situation
ABOUT Controller

public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult IndexSynchronous(string city)
        {
           System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            NewsService newsService = new NewsService();
            string[] headlines = newsService.GetHeadlines();
            SportsService sportsService = new SportsService();
            string[] scores = sportsService.GetScores();
            WeatherService weatherService = new WeatherService();
            string[] forecast = weatherService.GetForecast();
            watch.Stop();
            TimeSpan timeSpan = watch.Elapsed;
            return Content(timeSpan.ToString());
        }
    }



关于服务等级


ABOUT CLASS FOR SERVICE

public class NewsService
    {     
        public string[] GetHeadlines()
        {
            Thread.Sleep(8000);
            string[] strs = { "关于赵薇的童年", "关于王宝强的童年" };
            return strs;
        }
    }
 public class SportsService
    {
        public string[] GetScores()
        {
            Thread.Sleep(8000);
            string[] strs = { "第一名分数为11", "第二名分数为22" };
            return strs;
        }
    }
 public class WeatherService
    { 
       public string[] GetForecast()
        {
            Thread.Sleep(8000);
            string[] strs = { "关于赵薇的童年", "关于王宝强的童年" };
            return strs;
        }
    }



网址:http:// localhost:51424 /默认/ IndexSynchronous

结果:00: 00:24.0008085

以下示例显示了新闻门户网站索引操作方法的异步版本。

2:异步情况

关于AsyncController


URL:http://localhost:51424/Default/IndexSynchronous
RESULT:00:00:24.0008085
The following example shows an asynchronous version of the news portal Index action method.
2:Asynchronous situation
ABOUT AsyncController

public class DefaultController : AsyncController
   {
               System.Diagnostics.Stopwatch watch = new     System.Diagnostics.Stopwatch();
       public void IndexAsync(string city)
       {
           watch.Start();
           AsyncManager.OutstandingOperations.Increment(3);
           NewsService newsService = new NewsService();
           newsService.GetHeadlinesCompleted += (sender, e) =>
           {
               AsyncManager.Parameters["headlines"] = e.strs;
               AsyncManager.OutstandingOperations.Decrement();
           };
           newsService.GetHeadlinesAsync();

           SportsService sportsService = new SportsService();
           sportsService.GetScoresCompleted += (sender, e) =>
           {
               AsyncManager.Parameters["scores"] = e.strs;
               AsyncManager.OutstandingOperations.Decrement();
           };
           sportsService.GetScoresAsync();

           WeatherService weatherService = new WeatherService();
           weatherService.GetForecastCompleted += (sender, e) =>
           {
               AsyncManager.Parameters["forecast"] = e.strs;
               AsyncManager.OutstandingOperations.Decrement();
           };
           weatherService.GetForecastAsync();

       }

       public ActionResult IndexCompleted(string[] headlines, string[] scores, string[] forecast)
       {
           string stsHeadlines = "";
           for (int i = 0; i < headlines.Length; i++)
           {
               stsHeadlines += headlines[i];
           }
           string stsScores = "";
           for (int i = 0; i < scores.Length; i++)
           {
               stsScores += scores[i];
           }
           string stsForecast = "";
           for (int i = 0; i < forecast.Length; i++)
           {
               stsForecast += forecast[i];
           }
           watch.Stop();
           TimeSpan timeSpan = watch.Elapsed;
           return Content(timeSpan.ToString() + stsHeadlines + stsScores + stsForecast);

       }



关于服务等级


ABOUT CLASS FOR SERVICE

public class NewsService
    {
        public string[] strs;
        public delegate void GetHeadlinesCompletedEventHandler(object Sender, GetHeadlinesCompletedEventArgs e);
        public event GetHeadlinesCompletedEventHandler GetHeadlinesCompleted;
        public class GetHeadlinesCompletedEventArgs :EventArgs
        {
            public readonly string[] strs;
            public GetHeadlinesCompletedEventArgs(string[] strs)
            {
                this.strs = strs;
            }
        }
        protected virtual void OnGetHeadlinesCompleted(GetHeadlinesCompletedEventArgs e)
        {
            if (GetHeadlinesCompleted != null)
            {  
                GetHeadlinesCompleted(this, e);   
            }
        } 
        public async void  GetHeadlinesAsync()
        {
            string[] result = await GetValueAsync();
           GetHeadlinesCompletedEventArgs e = new GetHeadlinesCompletedEventArgs(result);
           OnGetHeadlinesCompleted(e);
        }
        public Task<string[]> GetValueAsync( )
        {
            return Task.Run(() =>
            {
                Thread.Sleep(8000);
                string[] strss = { "关于赵薇的童年", "关于王宝强的童年" };
                return strss;
            });
        }
    }

  public class SportsService
    {
        public string[] strs;
        public delegate void GetScoresCompletedEventHandler(object Sender, GetScoresCompletedEventArgs e);
        public event GetScoresCompletedEventHandler GetScoresCompleted;
        public class GetScoresCompletedEventArgs : EventArgs
        {
            public readonly string[] strs;
            public GetScoresCompletedEventArgs(string[] strs)
            {
                this.strs = strs;
            }
        }
        protected virtual void OnGetScoresCompleted(GetScoresCompletedEventArgs e)
        {
            if (GetScoresCompleted != null)
            { 
                GetScoresCompleted(this, e);   
            }
        }
        public async void GetScoresAsync()
        {
            string[] result = await GetValueAsync();
            GetScoresCompletedEventArgs e = new GetScoresCompletedEventArgs(result);
            OnGetScoresCompleted(e);
        }
        public Task<string[]> GetValueAsync()
        {
            return Task.Run(() =>
            {
                Thread.Sleep(8000);
                string[] strs = { "第一名分数为11", "第二名分数为22" };
                return strs;
            });
        }
    }

 public class WeatherService
    {
        public string[] strs;
        public delegate void GetForecastCompletedEventHandler(object Sender, GetForecastCompletedEventArgs e);
        public event GetForecastCompletedEventHandler     GetForecastCompleted;
        public class GetForecastCompletedEventArgs : EventArgs
        {
            public readonly string[] strs;
            public GetForecastCompletedEventArgs(string[] strs)
            {
                this.strs = strs;
            }
        }
        protected virtual void OnGetForecastCompleted(GetForecastCompletedEventArgs e)
        {
            if (GetForecastCompleted != null)
            {  
                GetForecastCompleted(this, e);   
            }
        } 
        public async void GetForecastAsync()
        {
            string[] result = await GetValueAsync();
            GetForecastCompletedEventArgs e = new GetForecastCompletedEventArgs(result);
            OnGetForecastCompleted(e);
        }
        public Task<string[]> GetValueAsync()
        {
            return Task.Run(() =>
            {
                Thread.Sleep(8000);
                string[] strs = { "关于赵薇的童年", "关于王宝强的童年" };
                return strs;
            });
        }

    }



网址:http:// localhost:51424 /默认/索引

结果:


URL:http://localhost:51424/Default/Index
RESULT:

00:00:08.0519411





我尝试过:





What I have tried:

var newsService = new NewsService();
  var sportsService = new SportsService();

  return View("Common",
      new PortalViewModel {
      NewsHeadlines = await newsService.GetHeadlinesAsync(),
      SportsScores = await sportsService.GetScoresAsync()
  });

推荐答案

当你使用 await 时,剩余的在您等待的任务完成之前,方法不会执行。如果该任务需要8秒,则下一个任务将在至少8秒后才开始。



您需要立即启动所有三个任务,然后等待它们全部完成。

When you use await, the rest of the method doesn't execute until the task you're waiting for has finished. If that task takes 8 seconds, the next task won't start until at least 8 seconds later.

You need to start all three tasks at once, then wait for them all to finish.
public async Task<ActionResult> IndexAsync(string city)
{
    var watch = System.Diagnostics.Stopwatch.StartNew();
    
    // Start all three tasks:
    
    var newsService = new NewsService();
    var newsTask = newsService.GetHeadlinesAsync(); // NB: No "await" here
    
    var sportsService = new SportsService();
    var sportsTask = sportsService.GetScoresAsync(); // Or here
    
    var weatherService = new WeatherService();
    var weatherTask = weatherService.GetForecastAsync(); // Or here
    
    // Wait for all three tasks to finish:
    await Task.WhenAll(newsTask, sportsTask, weatherTask);
    
    // Get the results:
    string[] headlines = await newsTask;
    string[] scores = await sportsTask;
    string[] forecast = await weatherTask;
    
    watch.Stop();
    
    TimeSpan timeSpan = watch.Elapsed;
    return Content(timeSpan.ToString());
}



注意:使用 async 会更简单并且等待使您的测试服务异步:


NB: It would be much simpler to use async and await to make your test services asynchronous:

public class NewsService
{     
    public async Task<string[]> GetHeadlinesAsync()
    {
        await Task.Delay(8000);
        string[] strs = { "...", "..." };
        return strs;
    }
}



另外, AsyncController类 [ ^ ]仅用于向后兼容MVC 3.假设您使用的是v4或更高版本,它已不再需要了。您可以让您的操作返回任务< T> 了。


Also, the AsyncController class[^] is only provided for backwards-compatibility with MVC 3. Assuming you're using v4 or later, it's no longer required. You can just make your actions return a Task<T> instead.


这篇关于异步控制器的任务支持,关于如何实现“sportsservice”的类。通过TAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆