elios264
elios264

Reputation: 404

Change the cursor when UI is busy

I have this class:

public class CursorWait : IDisposable
{
    private readonly CancellationTokenSource _tokenSource;

    public CursorWait(int showAfter)
    {
        _tokenSource = new CancellationTokenSource();
        Task.Delay(showAfter, _tokenSource.Token).ContinueWith(delegate(Task task)
        {
            if (!task.IsCanceled)
                Mouse.SetCursor(Cursors.Wait);
        });
    }

    public void Dispose()
    {
        _tokenSource.Cancel();
        Mouse.SetCursor(Cursors.Arrow);
    }
}

To use it like this :

using (new CursorWait(showAfter: 500))
{
    DoSomethingMayBeHeavyOrNotInUI(); 
}

However is not working since the Mouse.SetCursor relies in the UI thread to change it, and since it is busy, it will never change, so how can I change the cursor ?

Note: I know I should not be blocking the UI thread and instead just changing the property IsHitTestVisible of the window. but I'm new at this project and my team made the things this way, and they won't let me since the project is almost finished

Upvotes: 1

Views: 984

Answers (2)

B.K.
B.K.

Reputation: 10172

Application.Current.Dispatcher.Invoke(new Action(()=>
    {
        // your code
    }));

or

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
    new ThreadStart(delegate
        {
            // your code
        }));

More information at: MSDN - Dispatcher.Invoke Method

Upvotes: 1

Bradley Uffner
Bradley Uffner

Reputation: 17001

Try adding this line After setting the mouse cursor.

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));

Upvotes: 2

Related Questions