Prompt that takes long time to evaluate

Sometimes when working in posh console I need to see what GIT branch I use. After a while I found similar question on StackOverflow. I tried it, but noticed that evaluating the prompt function is rather slow.

Shortly it turned out that it's because of the code that evaluates different files. So, I removed the code and everything was fine. However, I was still wondering if it is possible to find the different files, but have a quick prompt at the same time.

Background jobs might help

One possible solution comes with background jobs. Simply start the job at the beginning of the session and query the job everytime prompt is evaluated. An example with querying google.com every 10 seconds continues:

# this code would be in profile file
# but as a demo, just copy&paste it into your console
Start-Job -name prompthelp {
  $cli = New-Object Net.WebClient
  while($true) {
    "{0}-{1}" -f (get-date), $cli.DownloadString('http://www.google.com').Length
    Start-Sleep -sec 10
  }
}

function prompt {
  $lengths = @(Receive-Job -name prompthelp)
  if ($lengths) {
    $global:__lastPrompt = $lengths[-1]
  }
  # now $global:__lastPrompt contains last item even when Receive-Job
  # didn't return anything, because previous prompt removed it
  if ($global:__lastPrompt) {
    "$global:__lastPrompt> "
  } else {
    "?> "
  }
}

And the following code simulates slowness of the original prompt function from SO.

function prompt {
  $cli = New-Object Net.WebClient
  "{0}-{1}" -f (get-date), $cli.DownloadString('http://www.google.com').Length
}

Bear in mind that asking for google home page length is really fast compared to the git diff-index command.

Meta: 2011-06-12, Pepa

Tags: PowerShell