doukao5073 2018-12-07 21:23
浏览 220
已采纳

了解Golang上下文超时

I am having trouble understanding how I can check if context exceeded deadline set by timeout, or if I should check at all?

This is a snippet from mongo-go-driver:

client, err := NewClient("mongodb://foo:bar@localhost:27017")
if err != nil { return err }
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil { return err }

Reading this code, how do I know if context exceeded deadline? From what I naively understand (or not understand), the line err = client.Connect(ctx) will give me error including deadline exceeded (if exceeded), thus I think I don't even need to explicitly check?

But then while looking around the internet to better understand how contexts work, I come across uses of select cases which explicitly checks contexts as below (code snippet from http://p.agnihotry.com/post/understanding_the_context_package_in_golang/):

//Use a select statement to exit out if context expires
  select {
  case <-ctx.Done():
    fmt.Println("sleepRandomContext: Time to return")
  case sleeptime := <-sleeptimeChan:
    //This case is selected when processing finishes before the context is cancelled
    fmt.Println("Slept for ", sleeptime, "ms")
  }

Should I be explicitly checking for it? If not, when should I use explicit checks? Thank you for your time and help!

  • 写回答

2条回答 默认 最新

  • doupu5941 2018-12-07 21:38
    关注

    The select code in the second part of your question is what the code in the Connect method might look like. There it is checking whether the ctx.Done() is ready to send. If it is, then the context was cancelled either because the timeout occurred, or because cancel() was called.

    errors are values. Treat them as such. If it is important for you to understand the cause of the error (network down? unexpected data? timeout?) then you should do the check and act accordingly. If recovery from the error regardless of the cause is the same, then checking the error is not as important.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里