0

As I know using async/await is equivalent for Task.Run with TaskScheduler.FromCurrentSynchronizationContext(). But I faced with embarrassment when try this (Xamarin.Forms environment):

Action ReFocus = async () =>
{
    // not work well as next somehow
    adresseeEntry.Unfocus();
    await Task.Run(() => {});
    adresseeEntry.Focus();
};
ReFocus();

This doesn't work like the following code:

Action ReFocus = () =>
{
    adresseeEntry.Unfocus();
    Task.Factory.StartNew<bool>(() => true).ContinueWith(r =>
    {
        adresseeEntry.Focus();
    }, TaskScheduler.FromCurrentSynchronizationContext());//*/
};
ReFocus();

Maybe on focusing an element is not a very good example. But this is a real situation that I encountered in practice (in the first case, the focus does not happen for some reason).

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 2
    It should be the same. What are you finding different? – Paulo Morgado Mar 17 '20 at 19:23
  • Is this all your code or you have omitted something? Is there any `ConfigureAwait(false)` after some previous `await`? – Theodor Zoulias Mar 17 '20 at 23:22
  • 1
    Fire-and-forget code is dangerous. If the async code fails with an exception then you'll never see it. – Hans Passant Mar 17 '20 at 23:35
  • @PauloMorgado, in the first case, there is no element focus, like in the second case – Александр Mar 19 '20 at 10:55
  • @TheodorZoulias, nop. In my code never used the `ConfigureAwait` method – Александр Mar 19 '20 at 10:56
  • @HansPassant, this probably seems to be true. I have already encountered the fact that in parallel threads, Xamarin does not handle my errors, but only completes the execution of threads . At the same time, the program runs on as if nothing had happened. Is that what you mean? – Александр Mar 19 '20 at 11:01
  • Is there anything you miss out in the post? These two piece of code snippet just works the same on my side. Refer to earlier post https://stackoverflow.com/questions/38423472/what-is-the-difference-between-task-run-and-task-factory-startnew, answer by Mykhailo Seniutovych, there's still some difference between these two usages. – Lia Mar 23 '20 at 09:16

0 Answers0