doucong3048 2017-08-12 19:04
浏览 22
已采纳

defer:在长时间运行的功能中使用?

Here is a sample function that takes a connection to the database from the connection pool and does a query and processes the result returned.

func dbQuery() error {
    con := db.getConn()
    result, err := con.Query()
    if err != nil {
       return err
    }
    defer con.close() // or con.close()
    // Processing the result takes a long time


    return nil
}

Processing the result in this case takes a long time and close is not called for the connection, which means it is not returned to the connection pool.
Is it ok to directly call con.close() in cases like this when we know the resources are held for a long time even when they are not needed?

  • 写回答

2条回答 默认 最新

  • duanbei1598 2017-08-12 19:28
    关注

    My suggestion would be to refactor your code. This way a defer closes the connection before you process the result:

    func dbQuery() error {
        result, err := getResult()
        if err != nil {
            return err
        }
        // Processing the result takes a long time
    
        return nil
    }
    
    func getResult() (*Rows, error) {
        con := db.getConn()
        defer con.close() // or con.close()
    
        result, err := con.Query()
        if err != nil {
            return nil, err
        }
    
        return result, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图