Discovering background threads on Windows Mobile
This isn’t actually all that amazing to anyone that already knows how to use the .Net Compact Framework on Windows Mobile devices. It’s interesting to me because I’m only recently started on application programming, let alone creating applications for my phone.
My discovery this evening is that it is incredibly simple to make my phone run C# code while it is in sleep mode, by just using threading. This opens up quite a few ideas for me which help me progress towards a better Jaiku-like client for my phone:
- I can send “Keep-Alive” packets at regular intervals to make sure my XMPP connection to Jabber didn’t time out.
- I can automatically find out the current cell tower I’m connected to at regular intervals - and possibly also send these straight to Jaiku and the web by SMS/GPRS. (Update: this is now implemented in my GSM Stumbler application)
- I can scan for nearby bluetooth devices and wireless networks throughout the day.
All that while my phone is looking harmless and the screen is completely off, very handy:
ThreadStart starter = new ThreadStart(this.FindCurrentLocation); Thread backgroundThread = new Thread(starter); backgroundThread.Start();
Very interesting idea really. Although I am just wondering, how much effect it will have on mobile’s battery life?
99% of the time it will be idle doing a
Thread.Sleep(). It will have a hit on the battery life, but not as much as having the device turned on.Hi David,
Am new to multi-threading in general in the .NET framework and wondered if you could elaborate on how you would use your code above to actually run code. I am running some syncronisation code in the background and would like to update some UI controls with the results (in this case it is a label with the “last updated time”). Is this easy enough to do? Any pointers in the right direction would be well appreciated
Rgds,stephen
Based on some code from agsXMPP, I discovered that the Windows Forms are not thread safe. This means that you can’t directly update the form controls from a background thread. I personally use a Timer control to update the UI. You could also use “Invoke”, but I’ve had less experience there.
Microsoft have a good quickstart tutorial and Multi-Threading Tips article for more information on implementing threading.
Hi David,
i’m addressing the same problem. However I’ve tested a thread sending a packet over the network every 15 seconds and when the device is in sleep mode, it sends them every 60 seconds. Does anyone know how to sort this out in order to get the right timing?
PS. The temporization inside the thread is achieved through a Thread.Sleep(15000) call.
Regards,
Daniel