0

As a hobby lately I have been doing a Piano (Midi) to keyboard software, but I have encountered a problem, to be able to be listening and executing several keys at the same time I have decided to use if and else if, but I understand that the program is using enough resources from the cpu and when an if is activated

Example 1 for On Note:

if (RawNotes.Contains ("Len: 0") == true && RawNotes.Contains ("0 NoteOn Ch: 1 C") == true && RawNotes.Contains ("#") == false)

Example 2 for Off Note:

else if (RawNotes.Contains("Vel") == true && RawNotes.Contains("0 NoteOn Ch: 1 C") == true && RawNotes.Contains("#") == false)

inspect the RawNotes string

Example RawNotes String Output

this string is constantly changing, thats the Output that the string gives me using Console.WriteLine(RawNotes);

0 NoteOn Ch: 1 C3 Vel: 41 Len: 0 //<-- NoteOn
0 TimingClock
0 TimingClock
0 TimingClock
0 TimingClock
0 NoteOn Ch: 1 C3 Vel: 0 //  <-- NoteOff
0 AutoSensing
0 TimingClock

And the main part of the code, it is only possible to execute for a few seconds since the if says so?

 Thread One = new Thread(() =>
{
     while (true)
                    {
                        if (RawNotes.Contains ("Len: 0") == true && RawNotes.Contains ("0 NoteOn Ch: 1 C") == true && RawNotes.Contains ("#") == false)

                        {
                            sim.Keyboard.KeyDown((VirtualKeyCode)Enum.Parse(typeof(VirtualKeyCode), Key1)); // <-- The problem
                        }

 else if (RawNotes.Contains("Vel") == true && RawNotes.Contains(MultiHelp + "C") == true && RawNotes.Contains("#") == false)
                        {
                            sim.Keyboard.KeyUp((VirtualKeyCode)Enum.Parse(typeof(VirtualKeyCode), Key1));

//And so on...
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • can you give an example od the rawnotes string? – Bacon Sep 13 '19 at 23:20
  • Ok, I added the string in the Questions – Diego Acevedo Sep 13 '19 at 23:42
  • You should parse `RawNotes` only when it got a new value. When communicating between threads, you should not use a plain variable but some kind of message. – CL. Sep 14 '19 at 07:09
  • What is the "sim" variable? Is it an instance of [InputSimulatorStandard](https://github.com/GregsStack/InputSimulatorStandard), or one of the other forks of Michael Noonan's Windows Input Simulator? If so, you need to understand how to [update the GUI from a background thread](https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread). – Former contributor Sep 14 '19 at 08:10
  • Looks very strange to rely on some string that should be parsed in order to send MIDI event. Can you at least subscribe on `RawNotes` changing and get rid of `while` loop (it's the reason why you see high CPU usage)? Also I think you need perform parsing within `lock` section. – Maxim Sep 30 '19 at 08:55

0 Answers0