首页 \ 问答 \ 使用Statement和ADO.NET对象(using Statement And ADO.NET Objects)

使用Statement和ADO.NET对象(using Statement And ADO.NET Objects)

考虑以下方法......

private string[] GetExistingPOWSNumbers()
{
    using (
        var OleAdapter =
            new OleDbDataAdapter(
                "SELECT DISTINCT con_num FROM `Items` WHERE con_num LIKE 'POWS%'",
                ConfigurationManager.ConnectionStrings["MPOleConnectionString"].ConnectionString))
    using (var POWSTable = new DataTable())
    {
        OleAdapter.SelectCommand.Connection.Open();
        OleAdapter.Fill(POWSTable);
        return POWSTable.AsEnumerable().Select(row => Convert.ToString(row["con_num"])).ToArray();
    }
}

是否所有ADO.NET对象都被及时处理? 我在整个项目中都使用这种方法,当在一次操作中有很多这样的调用时,我收到“Out of Memory”错误。

编辑:经过一些个人调查后,我发现,实际上,适配器的using语句也不会关闭提供的集合。 我做了以下改变。 现在我使用DataReader而不是填充DataTable。

private string[] GetExistingPOWSNumbers()
{
    var Results = new List<string>();
    using (var OleConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["MPOleConnectionString"].ConnectionString))
    using (
        var OleCommand =
            new OleDbCommand(
                "SELECT DISTINCT con_num FROM `Items` WHERE con_num LIKE 'POWS%'",
                OleConnection))
    {
        OleConnection.Open();
        using (var OleReader = OleCommand.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (OleReader == null) return new string[0];
            while (OleReader.Read())
            {
                Results.Add(OleReader.GetString(0));
            }
        }
    }
    return Results.ToArray();
}

Consider the following method...

private string[] GetExistingPOWSNumbers()
{
    using (
        var OleAdapter =
            new OleDbDataAdapter(
                "SELECT DISTINCT con_num FROM `Items` WHERE con_num LIKE 'POWS%'",
                ConfigurationManager.ConnectionStrings["MPOleConnectionString"].ConnectionString))
    using (var POWSTable = new DataTable())
    {
        OleAdapter.SelectCommand.Connection.Open();
        OleAdapter.Fill(POWSTable);
        return POWSTable.AsEnumerable().Select(row => Convert.ToString(row["con_num"])).ToArray();
    }
}

Are all the ADO.NET objects promptly being disposed of? I am using this method throughout my projects and when there are A LOT of calls like these being made during a single action, I receive "Out of Memory" errors.

EDIT: After some personal investigation I discovered that, in fact, the using statement for the adapter DOES NOT also close the provided collection. I made the following change. Now I am using a DataReader instead of populating a DataTable.

private string[] GetExistingPOWSNumbers()
{
    var Results = new List<string>();
    using (var OleConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["MPOleConnectionString"].ConnectionString))
    using (
        var OleCommand =
            new OleDbCommand(
                "SELECT DISTINCT con_num FROM `Items` WHERE con_num LIKE 'POWS%'",
                OleConnection))
    {
        OleConnection.Open();
        using (var OleReader = OleCommand.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (OleReader == null) return new string[0];
            while (OleReader.Read())
            {
                Results.Add(OleReader.GetString(0));
            }
        }
    }
    return Results.ToArray();
}

原文:https://stackoverflow.com/questions/37122443
更新时间:2022-10-20 16:10

最满意答案

您仍然需要使用带有promise的回调函数:

doSomethingDN (var1, var3)
.then(function(data) {
//    ^^^^^^^^^^^^^^^^
    if (!data) {
        return doAnotherThingDN(var1,var2)
    }
}); /*
^

你得到一个语法错误,因为你把函数体正确作为参数。


You still need to use a callback function with promises:

doSomethingDN (var1, var3)
.then(function(data) {
//    ^^^^^^^^^^^^^^^^
    if (!data) {
        return doAnotherThingDN(var1,var2)
    }
}); /*
^

You were getting a syntax error because you put the function body right as the argument to then.

相关问答

更多
  • 看起来像this.UpdateListItem函数已经通过$promise对象返回$promise 。 这就是为什么你能够拥有.then (连锁承诺)功能的原因。 所以基本上你只需要推送返回的itemPromise对象而不是在promises数组中使用itemPromise.$promise 。 基本上当你做$promise ,它会创建一个[undefined, undefined, ...]数组,并在循环完成后立即解析。 改成 promises.push(itemPromise) 从 promises. ...
  • 没有“执行承诺”这样的事情。 Promise是异步操作结果的代理。 执行承诺与执行数字5相似。 你可以同步执行的是返回promise的函数。 这是reduce可以做的。 您可以使用allSettled原语而不是allSettled : var functions = [promiseReturningFn1, promiseReturningFn2, promiseReturningFn3]; functions.reduce((soFar, current) => { return soFar.the ...
  • 是的,这有点奇怪,但有一点不同:将使用结果数组而不是结果本身调用responseFunc 。 这可能最好写成两者 promise.then(res => responseFunc([res])) 要么 promise.then(Array.of).then(responseFunc) Yes, this is a bit weird, but there is a difference: responseFunc will be called with an array of the result in ...
  • 我认为db.run不是函数而是方法。 来自Q doc: 如果你正在使用方法而不是简单的函数,你可以很容易地遇到将方法传递给另一个函数的常见问题,比如Q.nfcall-从它的所有者“取消绑定”该方法。 为避免这种情况,您可以使用Function.prototype.bind或我们提供的一些不错的快捷方法: return Q.ninvoke(redisClient, "get", "user:1:id"); return Q.npost(redisClient, "get", ["user:1:id"]); ...
  • 您仍然需要使用带有promise的回调函数: doSomethingDN (var1, var3) .then(function(data) { // ^^^^^^^^^^^^^^^^ if (!data) { return doAnotherThingDN(var1,var2) } }); /* ^ 你得到一个语法错误,因为你把函数体正确作为参数。 You still need to use a callback function with promises: do ...
  • 对then的调用也会返回一个promise。 然后,您可以将其传递给您的数组而不是原始的承诺。 这样你的$q.all将在所有你的执行完毕后运行。 var promises = []; for(i=1, i<5, i++){ // singlePromise - this is now a new promise from the resulting then var singlePromise = SomeSevice.getData().then(function(data){ ...
  • 我将简化3个承诺中的每一个(特别是1和3),以便this.locations,this.states和this.territories都在$ q.all中更新。然后 - 你不必,但我认为它使代码更具可读性 接下来,将所有3个promises分配给变量(下面的代码中的p1,p2,p3) 下一个问题是等待所有状态API调用完成 - 那里需要另一个$ q.all 总而言之,有了额外的ES6优点,你就得到了 getAllLocations() { //first prmise const p1 = ...
  • 当函数具有实际返回所需的所有数据时,您要做的是在promise上调用resolve函数 在返回promise的函数中,将“resolve”视为实际的return语句。 所以你的isLoggedInPromise函数也需要返回一个promise,这会让它变得多余。 任何需要用户的东西都必须等待它。 isLoggedInPromise().then(function(result){...etc...}, function(reason){//auth needed}) 如果你仍然需要isLoggedin函数, ...
  • 您可以返回firstResponse和methodB的结果: let deferred = Q.Promise(); this.methodA('somevalue') .then(firstResponse => { return Q.all([this.methodB(firstResponse.prop1), Q(firstResponse.prop1)]; }).then(secondResponse => { return Q.all([this.meth ...
  • 有一点是你需要注入$rootScope才能使用它: app.service('LoadData', ['FeedService', 'EntryStateUrlService', '$q', '$rootScope', function(FeedService, EntryStateUrlService, $q, $rootScope) { //... } ]); 同样在Q库中有一个名为allSettled的方法,它允许您查看所有的promise结果,即使一个失败也是如此。 角度$ q没有这种 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)