Musical chairs: How can an asynchronous task cancel a synchronous one in c#?

51 Views Asked by At

I’m writing a program in C# for a windows forms application in .NET Framework.

My program plays musical chairs.

There is a method that runs synchronously and takes about 60 seconds to run, let's call it DanceMoves().

This method needs to run in a loop until the condition hasMusic is false.

The condition hasMusic is being modified in another task, asynchronously.

The exact moment when this condition is met, not only should the loop break, but the synchronous method DanceMoves() should be aborted immediately so we can run the GrabChair() method.

So if it happens when 25 seconds have passed, it shouldn't finish the last 35 seconds of the DanceMoves() method, it should just immediately be aborted and run the GrabChair() method.

I cannot modify the synchronous method DanceMoves();

How can I acheive this?

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MusicalChairs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            // Do not modify this method
            InitializeComponent();
        }

        private bool hasMusic = true;
        private Random random = new Random();
        private async void StartMusicButton_Click(object sender, EventArgs e)
        {
            hasMusic = true; 
            ChangeMusicStatusAsync();
            while (hasMusic)
            {
                DanceMoves();
            }
            GrabChair();
        }

        private async Task ChangeMusicStatusAsync()
        {
            // Do not modify this method
            await Task.Delay(random.Next(1, 11) * 20000);
            hasMusic = false;
        }

        private void DanceMoves()
        {
            // Do not modify this method
            Thread.Sleep(60000);
        }

        private void GrabChair()
        {
            // Do not modify this method
        }
    }
}
0

There are 0 best solutions below