A191919
A191919

Reputation: 3442

IAsyncResult cancelTokenSource

Why does the mouse movement after clicking on the cancel button not stop?

Xaml:

<Button Height="20" Width="40" Click="Button_Click"></Button>

Code:

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {

        WorkWithMouse WWM = new WorkWithMouse();

        public MainWindow()
        {
            InitializeComponent();
            WWM.MouveMouseAsync();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            WWM.AbortMouseMove();
        }
    }

    public class WorkWithMouse
    {
        CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

        [DllImport("User32.dll")]
        private static extern bool SetCursorPos(int X, int Y);

        public void AbortMouseMove()
        {
            cancelTokenSource.Cancel();
        }

        public void MouveMouseAsync()
        {
            Action<CancellationToken> task = new Action<CancellationToken>(MoveMouse);
            IAsyncResult result = task.BeginInvoke(cancelTokenSource.Token, null, null);
        }
        private void MoveMouse(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                for (int i = 100; i < 500; i++)
                {
                    System.Threading.Thread.Sleep(2000);
                    SetCursorPos(i, 100);
                }
            }
        }
    }
}

Upvotes: 1

Views: 192

Answers (1)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

It doesn't stop because you only check for the cancellation of the token in the outer while loop and your inner for loop goes on for a few more minutes. You could however add a simple if check in or to your for loop.

for (int i = 100; i < 500; i++)
{
    if (token.IsCancellationRequested) break;

    System.Threading.Thread.Sleep(2000);
    SetCursorPos(i, 100);
}

or inline:

for (int i = 100; (i < 500) && (!token.IsCancellationRequested); i++)
{
    System.Threading.Thread.Sleep(2000);
    SetCursorPos(i, 100);
}

Upvotes: 2

Related Questions