简体   繁体   English

C#从Task with oledb返回值

[英]C# return value from Task with oledb

I am accessing XLSX Files and summing up the [FileSize] Values of a Column, it contains more than 100k rows. 我正在访问XLSX文件并总结列的[FileSize]值,它包含超过100k行。

I wanted to use OLEDB in combination with multitasks. 我想将OLEDB与多任务组合使用。 After that I want the tasks to return an integer/float value so I can calculate the percentage of each XLSX file compared to the total file size. 之后,我希望任务返回一个整数/浮点值,这样我就可以计算每个XLSX文件与总文件大小的百分比。 So far I have this code: 到目前为止,我有这个代码:

foreach (string subdir in alldir)
{
    Task<int> iSize = Task<int>.Factory.StartNew(() =>
    {
        int result = 0;
        using (OleDbConnection olecnn = new OleDbConnection(GetConnectionString(subdir)))
        {
            try
            {
                olecnn.Open();
                using (OleDbCommand sumcmd = new OleDbCommand("SELECT SUM([File Size]) FROM [FileInfos$]"))
                {
                    sumcmd.Connection = olecnn;
                    result = (int)sumcmd.ExecuteScalar();
                    //BarChart.Series["Memory Usage"].Points.AddXY(Path.GetFileName(subdir), result);
                    return result;
                }
                olecnn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString()); return result;
            }

        }
    }).ContinueWith(cnt => cnt.Dispose());
}

There seems to be an syntax error 似乎存在语法错误

Cannot implicitly convert type ' System.Threading.Tasks.Tasks ' to ' System.Threading.Tasks.Task<int> '. 无法将类型' System.Threading.Tasks.Tasks '隐式转换为' System.Threading.Tasks.Task<int> '。 An explicit conversion exists (are you missing a cast)? 存在显式转换(您是否错过了演员表)?

I read the docs but can't figure out how to get the result as integer/float, so I can proceed with this value. 我阅读了文档,但无法弄清楚如何将result作为整数/浮点数,所以我可以继续这个值。

You start a task that returns an int result, and then follow it with another task in ContinueWith that can only return void - that's where the syntax error comes from. 您启动一个返回int结果的任务,然后使用ContinueWith中的另一个任务跟随它,该任务只能返回void - 这就是语法错误的来源。

Also, do you really need to call Dispose() inside ContinueWith? 另外,你真的需要在ContinueWith中调用Dispose()吗? Anything declared as a part of using block will call Dispose on itself even if an exception is thrown (see this blog post for explanation and code samples). 声明为使用块的一部分的任何内容都将调用Dispose自身,即使抛出异常(请参阅此博客文章以获取解释和代码示例)。

Also-2, answers to this post have some helpful info on why you usually shouldn't use Factory.StartNew (which is semi-obsolete): What is the difference between Task.Run() and Task.Factory.StartNew() 另外,2,这篇文章的答案有一些有用的信息,说明为什么你通常不应该使用Factory.StartNew(这是半过时的): Task.Run()和Task.Factory.StartNew()之间有什么区别?

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM