I am trying to implement cursor changing when my application making big issue. I was trying this
public class CursorWait : IDisposable
{
public CursorWait(bool appStarting = false, bool applicationCursor = false)
{
// Wait
Cursor.Current = appStarting ? Cursors.AppStarting : Cursors.WaitCursor;
if (applicationCursor) Application.UseWaitCursor = true;
}
public void Dispose()
{
// Reset
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
and also this
public static class UiServices
{
private static bool IsBusy;
public static void SetBusyState()
{
SetBusyState(true);
}
private static void SetBusyState(bool busy)
{
if (busy != IsBusy)
{
IsBusy = busy;
Mouse.OverrideCursor = busy ? Cursors.Wait : null;
if (IsBusy)
{
new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, Application.Current.Dispatcher);
}
}
}
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
var dispatcherTimer = sender as DispatcherTimer;
if (dispatcherTimer != null)
{
SetBusyState(false);
dispatcherTimer.Stop();
}
}
}
But both cases giving me error: The calling thread must be STA, because many UI components require this.
In my app, I am using special call to make some stuff on DB and user privileges. This code looks like this:
Task.Run(() => TryExecute(securedAction)).ContinueWith(taskResult =>
{
var application = Application.Current;
if (DoneActionCanBeDone(doneAction, taskResult))
{
if (application != null)
{
application.Dispatcher.InvokeAsync(() => doneAction(taskResult.Result));
}
else
{
doneAction(taskResult.Result);
}
}
else if (taskResult.Status != TaskStatus.RanToCompletion)
{
if (application != null)
{
application.Dispatcher.InvokeAsync(
() => InvokeRollbackAction(rollbackAction, suppressError, taskResult));
}
else
{
InvokeRollbackAction(rollbackAction, suppressError, taskResult);
}
}
});
My cursor changing should start before Task.Run and end after its ending. Thanks for advices.