0

I'm trying to show a waiting message via a Toast while a long operation is running. I'm using a BackgroundWorker. This code is inside a ListView_ItemClick event handler:

var bgWait = new BackgroundWorker();
bgWait.DoWork += bgWait_DoWork;
bgWait.RunWorkerAsync();
bgWait.RunWorkerCompleted += bgWait_Completed;

The code in bgWait_DoWork event handler is the following:

private void bgWait_DoWork(object sender, DoWorkEventArgs e)
{
var toastWait = Toast.MakeText(this, "Please wait", ToastLength.Long);
toastWait.SetGravity(GravityFlags.Top & GravityFlags.Center, 0, 0);
toastWait.Show();
TimeConsumingOperation();
toastWait.Cancel();
}

When I run in debug mode, it seems that only the first line from bgWait_DoWork is reached - "var toastWait = Toast.MakeText(this, "Please wait", ToastLength.Long);" - and then it jumps to bgWait_Completed event handler.

Any idea why this is happening?

Thanks

razvanSax
  • 87
  • 1
  • 8
  • I get an error related to the fact that the bgWait_DoWork is not completed. In the bgWait_Completed I'm using a result from bgWait_DoWork, so the error is right to happen. – razvanSax Nov 07 '12 at 10:19
  • well, post the related stack trace (or whatever it is called in mono), will you? – njzk2 Nov 07 '12 at 10:22
  • This is the exception message I get on the first line in bgWait_DoWork: LocalizedMessage = "Can't create handler inside thread that has not called Looper.prepare()" – razvanSax Nov 07 '12 at 10:28
  • 1
    see http://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare (not the same language, but same issue) – njzk2 Nov 07 '12 at 10:34

1 Answers1

2

You're calling UI-related API from a secondary thread (bgWait_DoWork is executed on a secondary thread).

You must instead do something like this:

private void bgWait_DoWork(object sender, DoWorkEventArgs e)
{
    Toast toastWait = null;
    RunOnUIThread (() => 
    {
        toastWait = Toast.MakeText(this, "Please wait", ToastLength.Long);
        toastWait.SetGravity(GravityFlags.Top & GravityFlags.Center, 0, 0);
        toastWait.Show();
    });
    TimeConsumingOperation();
    RunOnUIThread (() =>
    {
        toastWait.Cancel(); 
    });
}

}

Rolf Bjarne Kvinge
  • 19,253
  • 2
  • 42
  • 86