C# 从返回bool并返回到浏览器的方法中获取计数器值int

C# 从返回bool并返回到浏览器的方法中获取计数器值int,c#,jquery,asp.net-mvc,C#,Jquery,Asp.net Mvc,我正试图找出如何在foreach循环中的方法中获得计数器的值 我考虑过代表,但我不知道怎么做 我的方法是删除所有不相关的代码 public static bool ReadExcelFile(string str1, int Id, out int tCount) { int primaryCounter = 0; //Insert new items foreach (var item in excelList) {

我正试图找出如何在foreach循环中的方法中获得计数器的值

我考虑过代表,但我不知道怎么做

我的方法是删除所有不相关的代码

public static bool ReadExcelFile(string str1, int Id, out int tCount)
{
    int primaryCounter = 0;                    

    //Insert new items
    foreach (var item in excelList)
    {                
        primaryCounter++;                                
    }

    return true;
}                
然后我有一个ActionResults,用于jquery轮询

public ActionResult InsertPolling()
{
    int currentCount = //How to get value of counter        
    string pollingMessage = $"Inserted {currentCount}  items";
    return Json(pollingMessage, JsonRequestBehavior.AllowGet);
}
我的jQuery是:

function doPollHandler(event) {
    $.post('/UploadData/InsertPolling',
        function(data) {
            alert(data); // process results here
            setTimeout(window.doPollHandler, 2000);
        });
};

$('#fileUpload').change(function () {
    doPollHandler();
});
我看过


但是,由于我的方法返回bool,我需要获取counter的值,因此我一直在研究如何执行此操作。

希望这能帮助您理解使用委托的回调

namespace ConsoleApplication1
{
    class Program
    {

        public delegate void Del(int message);
        static void Main(string[] args)
        {
            Del handler = DelegateMethod;
            MethodWithCallback(handler);
        }

        public static void MethodWithCallback(Del callback)
        {
            for (int i = 0; i < 50; i++)
            {
                callback(i);

            }
        }
        public static void DelegateMethod(int primaryCounter)
        {
            System.Console.WriteLine(primaryCounter);
        }
    }
}
命名空间控制台应用程序1
{
班级计划
{
公共代表无效Del(int消息);
静态void Main(字符串[]参数)
{
Del handler=DelegateMethod;
MethodWithCallback(处理程序);
}
公共静态无效方法WithCallback(Del callback)
{
对于(int i=0;i<50;i++)
{
收回(i);
}
}
公共静态void DelegateMethod(int primaryCounter)
{
系统控制台写入线(主计数器);
}
}
}

在静态方法中,我假设
tCount
primaryCounter
不引用相同的东西?您可以只添加第二个
out
参数,但这看起来有点难闻。我们可能需要更详细的代码来给出一个简洁的答案@Rhumborl我不能使用tCount,因为它会在最后返回所有记录的计数,我想做的是每2秒获取primaryCounter的值,以便访问者可以看到进度。这不是Rhumborl所说的。Rhumborl说可以添加第二个
out
参数。并暗示如果你的方法返回不止一个东西,就像它已经做过的那样,考虑返回一个具有一些属性的简单对象来保存这些值,而不是返回<代码> BOOL 并具有<代码> OUT/<代码>参数。但是您需要在方法返回之前更新值,因此这对您没有帮助。