Pergunta

I have a method with the following code:

object frm = null;

// shows the overlay loading mask
Core.ShowLoadingMask("Please wait...");

// start task
Task.Factory.StartNew(() => {

    // go to server and get the data
    var employee = new Data.Entities.Employee(employeeId);

    // instantiate the class type (reflection)
    frm = Activator.CreateInstance(type, employee );

}).ContinueWith((task) => {

    // hide loading mas
    Core.HideLoadingMask();

    if (frm != null) this.Panel.Controls.Add(frm);

});

So, how can I force that the code inside ContinueWith() force to use the Current Thread, or maybe I'm doing it wrong.

The process I need is:

  1. Show Loading Mask before getting data from server
  2. Get data from server (could take 3 seconds)
  3. After that then exit the task and Hide the loading mask.

Any clue?

Foi útil?

Solução

Pass TaskScheduler.FromCurrentSynchronizationContext() to ContinueWith()...

.ContinueWith((task) => {
    // hide loading mas
    Core.HideLoadingMask();

    if (frm != null) this.Panel.Controls.Add(frm);
}, TaskScheduler.FromCurrentSynchronizationContext());

Outras dicas

Assuming that this is also a UI control, you can store the current dispatcher using this.Dispatcher before starting the task. Then in the ContinueWith, use the stored dispatcher to execute the hide operation. See Dispatcher.BeginInvoke.

Dispatcher dispatcher = this.Dispatcher;

Core.ShowLoadingMask("Please wait...");

return Task.Factory.StartNew(() =>
{
    doStuff();
    frm = ...
}).ContinueWith(t =>
{
    dispatcher.BeginInvoke(new Action(() =>
    {
        Core.HideLoadingMask();
        if (frm != null) this.Panel.Controls.Add(frm);
    }));
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top