JSON可以使用收益率返回“实时”返回吗?

时间:2012-09-01 22:35:29

标签: c# asp.net-mvc json asp.net-web-api

情况就是这样。

我在做什么:   - ASP.NET MVC 4 Web API   - IIS 7.0来托管应用程序   - C#

我有Web API从Intranet上的远程计算机获取性能数据,并且正在测试通过URL调用调用API,这将返回JSON。但是,它必须在返回JSON之前先完成执行。因此,例如,如果我将性能监控返回10秒,我将需要等待10秒才能显示所有数据值。

我想要做的就是让它生效,这样当它每秒读取性能计数器并以JSON显示它时会返回一个值,而不是等待检索所有内容然后立即列出所有内容。我试图使用YIELD关键字来完成此任务,但它仍然无法正常工作。在方法完成之前,JSON不会显示在浏览器中。

以下是存储库方法和协调控制器操作的代码:

来自LogDBRepository.cs:

public IEnumerable<DataValueInfo> LogTimedPerfDataLive(string macName, string categoryName, string counterName,
                                          string instanceName, string logName, long? seconds)
    {
        iModsDBRepository modsDB = new iModsDBRepository();
        List<MachineInfo> theMac = modsDB.GetMachineByName(macName);

        if (theMac.Count == 0)
            yield break;

        else if (instanceName == null)
        {
            if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
                !PerformanceCounterCategory.CounterExists(counterName, categoryName, macName))
            {
                yield break;
            }
        }
        else if (instanceName != null)
        {
            if (!PerformanceCounterCategory.Exists(categoryName, macName) ||
                !PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) ||
                !PerformanceCounterCategory.InstanceExists(instanceName, categoryName, macName))
            {
                yield break;
            }
        }
        else if (logName == null)
        {
            yield break;
        }

        // Check if entered log name is a duplicate for the authenticated user
        List<LogInfo> checkDuplicateLog = this.GetSingleLog(logName);
        if (checkDuplicateLog.Count > 0)
        {
            yield break;
        }

        PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, theMac[0].MachineName);
        if (category.CategoryName == null || category.MachineName == null)
        {
            yield break;
        }

        List<LogInfo> logIt = new List<LogInfo>();
        if (category.CategoryType != PerformanceCounterCategoryType.SingleInstance)
        {
            List<InstanceInfo> instances = modsDB.GetInstancesFromCatMacName(theMac[0].MachineName, category.CategoryName);

            foreach (InstanceInfo inst in instances)
            {
                if (!category.InstanceExists(inst.InstanceName))
                {
                    continue;
                }
                else if (inst.InstanceName.Equals(instanceName, StringComparison.OrdinalIgnoreCase))
                {
                    PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
                                                                        inst.InstanceName, theMac[0].MachineName);

                    //CounterSample data = perfCounter.NextSample();
                    //double value = CounterSample.Calculate(data, perfCounter.NextSample());
                    string data = "";
                    List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);

                    string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");

                    List<string> dataValues = new List<string>();
                    for (int i = 0; i < seconds; i++)
                    {
                        data = "Value " + i + ": " + perfCounter.NextValue().ToString();
                        DataValueInfo datItUp = new DataValueInfo
                        {
                            Value = data
                        };
                        yield return datItUp;
                        dataValues.Add(data);
                        Thread.Sleep(1000);
                    }
                    string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");

                    Log log = new Log
                    {
                        LogName = logName,
                        CounterName = perfCounter.CounterName,
                        InstanceName = perfCounter.InstanceName,
                        CategoryName = perfCounter.CategoryName,
                        MachineName = perfCounter.MachineName,
                        TimeStarted = timeStarted,
                        TimeFinished = timeFinished,
                        PerformanceData = string.Join(",", dataValues),
                        UserID = currUser[0].UserID
                    };
                    this.CreateLog(log);
                    break;
                }
            }
        }
        else
        {
            PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName,
                                                                        "", theMac[0].MachineName);


            string data = "";
            List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name);

            string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");

            List<string> dataValues = new List<string>();

            for (int i = 0; i < seconds; i++)
            {
                data = "Value " + i + ": " + perfCounter.NextValue().ToString();
                DataValueInfo datItUp = new DataValueInfo
                {
                    Value = data
                };
                yield return datItUp;
                dataValues.Add(data);
                Thread.Sleep(1000);
            }
            string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt");

            Log log = new Log
            {
                LogName = logName,
                CounterName = perfCounter.CounterName,
                InstanceName = perfCounter.InstanceName,
                CategoryName = perfCounter.CategoryName,
                MachineName = perfCounter.MachineName,
                TimeStarted = timeStarted,
                TimeFinished = timeFinished,
                PerformanceData = string.Join(",", dataValues),
                UserID = currUser[0].UserID
            };
            this.CreateLog(log);
        }

    }

来自LogController.cs:

[AcceptVerbs("GET", "POST")]
    public IEnumerable<DataValueInfo> Log_Perf_Data(string machine_name, string category_name, string counter_name, string instance_name,
                                   string log_name, long? seconds, string live, string enforceQuery)
    {
        LogController.CheckUser();

        // POST api/log/post_data?machine_name=&category_name=&counter_name=&instance_name=&log_name=&seconds=
        if (machine_name != null && category_name != null && counter_name != null && log_name != null && seconds.HasValue && enforceQuery == null)
        {
            List<DataValueInfo> dataVal = logDB.LogTimedPerfDataLive(machine_name, category_name, counter_name, instance_name,
                                   log_name, seconds).ToList();
            logDB.SaveChanges();
            foreach (var val in dataVal)
                yield return val;
        }

        yield break;   
    }

感谢您的时间和考虑。

1 个答案:

答案 0 :(得分:1)

yield仅在刷新响应时创建要返回的内存对象。

执行此操作的最简单方法可能是将json保存在服务器上的同步(静态?)变量中,当您请求显示您创建json的性能数据时,启动后台工作者(google for web backgrounder nuget)填充将数据转换为json对象,设置运行标志并返回json对象(开始时可能为空)。

然后,使用浏览器中的setInterval,每秒通过调用服务器来刷新此数据,因此每次获得包含越来越多数据的响应时。当后台线程完成时,你将running flag设置为false,并在下一次调用中返回你的json信息,这样你就可以停止从客户端刷新。

这是 NOT 最好的方法,但可能最容易实现。