Fix accessing the unread count using MessageProvider

Thanks to teslacoil for diagnosing the problem and coming up with a fix.
Fix some warnings
Make sure semaphore in MessageProvider is released in case of an error

Patch provided by teslacoil