I wrote a short C# script to execute when my computer starts up. Its function is to monitor iTunes and display a fun message as my Skype status stating what artist I'm listening to.
It creates an iTunesApp object and adds a listener which detects when the track changes. The problem is that I need to use a while(true)
loop to keep my app open in the background, or else it will just run and close. I thought this was okay until I looked in Task Manager and realized this small program is using 15%-20% of the CPU!
Is there a better approach?
Here is the heart of the code, to get an idea:
static void Main(string[] args)
{
iTunesApp = new iTunesAppClass();
iTunesApp.OnPlayerPlayEvent += ITunesApp_OnPlayerPlayEvent;
while (true)
{ }
}
private static void ITunesApp_OnPlayerPlayEvent(object iTrack)
{
var currentArtist = iTunesApp.CurrentTrack.Artist;
if (currentArtist != LastArtist)
{
LastArtist = currentArtist;
var message = GetMessage(currentArtist);
UpdateSkypeStatus(message);
UpdateLog(message);
}
}
The full project is at https://github.com/ericsundquist/SkypeTunes.
Wait with ManualResetEvent, and set() it when your program needs to close. In my example below call Stop to end your program.
static ManualResetEvent signal;
static void Main(string[] args)
{
iTunesApp = new iTunesAppClass();
iTunesApp.OnPlayerPlayEvent += ITunesApp_OnPlayerPlayEvent;
signal = new ManualResetEvent(false);
signal .WaitOne();
}
public static void Stop()
{
signal.Set();
}
private static void ITunesApp_OnPlayerPlayEvent(object iTrack)
{
var currentArtist = iTunesApp.CurrentTrack.Artist;
if (currentArtist != LastArtist)
{
LastArtist = currentArtist;
var message = GetMessage(currentArtist);
UpdateSkypeStatus(message);
UpdateLog(message);
}
}