logo
down
shadow

Using await with Task.Run but UI still hangs for a few seconds?


Using await with Task.Run but UI still hangs for a few seconds?

By : T.Dav
Date : November 22 2020, 11:12 AM
I wish did fix the issue. Presumably, nothing inside GetData or the Task.Run lambda inside SAPLogin is trying to callback the UI thread with Dispatcher.Invoke, Dispatcher.BeginInvoke or Dispatcher.InvokeAsync. Check for such possibility first.
Then, try changing your code like below. Note how Task.Factory.StartNew with TaskCreationOptions.LongRunning is used instead of Task.Run and how GetData is offloaded (despite it's already async, so mind .Unwrap() here). If that helps, try each change independently, to see which one particularly helped, or whether it was a combination of both.
code :
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Busy.Visibility = System.Windows.Visibility.Visible; // Shows progress animation

    if (await SAPLogin()) // Waits for login to finish, will always be true at the moment
    {
        //await GetData(); // does things with sap
        await Task.Factory.StartNew(() => GetData(),
            CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default).Unwrap();

        Busy.Visibility = System.Windows.Visibility.Collapsed; // Hides progress animation
    }
}

private Task<bool> SAPLogin()
{
    bool LoggedIn = true;

    return Task.Factory.StartNew(() =>
    {
        Backend = new BackendConfig();
        RfcDestinationManager.RegisterDestinationConfiguration(Backend);
        SapRfcDestination = RfcDestinationManager.GetDestination(MyServer);  // MyServer is just a string containing sever name

        SapRap = SapRfcDestination.Repository;

        BapiMD04 = SapRap.CreateFunction("MD_STOCK_REQUIREMENTS_LIST_API");

        BapiMD04.SetValue("WERKS", "140");

        return LoggedIn;
    }, 
    CancellationToken.None,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);
}


Share : facebook icon twitter icon
await works but calling task.Result hangs/deadlocks

await works but calling task.Result hangs/deadlocks


By : Roman Beltyukov
Date : March 29 2020, 07:55 AM
hop of those help? You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result.
In this case, your SynchronizationContext is the one used by NUnit to execute async void test methods. I would try using async Task test methods instead.
Using await Task<T> async hangs controller in MVC app

Using await Task<T> async hangs controller in MVC app


By : Vivek D.
Date : March 29 2020, 07:55 AM
may help you . You should probably turn the controller method into an async method and use await to avoid deadlocks.
code :
public async Task<ActionResult> MyActionAsync()
{
    var asdf = SharedTypes.Utilities.GetjsonStream(someUrl);
    string g = await asdf;
    // return something
}
Learning C#'s async/await/Task structure; code hangs at await?

Learning C#'s async/await/Task structure; code hangs at await?


By : suvendu
Date : March 29 2020, 07:55 AM
wish of those help You haven't actually run any Task. So you're waiting on something that will never complete.
To fix your code exactly as it is, you can do this:
code :
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = Task.Run(() => makeFoo());
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = makeFooAsync();
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}

async Task<Foo> makeFooAsync()
{
    await Task.Delay(3000);
    return new Foo();
}
private Task<Foo> RunExecute(bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        return makeFooAsync();
    }
    else
    {
        return Task.FromResult(makeFoo());
    }
}
Await Task hangs if creating a new form instance before running the task

Await Task hangs if creating a new form instance before running the task


By : user2478278
Date : March 29 2020, 07:55 AM
I hope this helps you . The other answers saying that you shouldn't be creating forms inside a console app or a unit test are absolutely correct.
From your updated code, it looks like someone has already gone to the trouble of making sure you can unit-test your presenter without having to instantiate your form: the FrmLoginPresenter constructor takes an IFrmLogin, which I'm assuming is an interface implemented by FrmLogin. This abstraction exists to allow you to unit-test FrmLoginPresenter without having to create an actual FrmLogin.
Task.WaitAll hangs with async/await tasks

Task.WaitAll hangs with async/await tasks


By : VCEssence
Date : March 29 2020, 07:55 AM
around this issue You exactly fall in deadlock on SynchronizationContext. Just use WhenAll instead of WaitAll:
Related Posts Related Posts :
  • Replace a # character with a space and a # character
  • DataGrid SelectedItem and CurrentItem on row change and on loosing focus
  • Parse Json to class with C#
  • Publish .exe with Visual Studio Mac
  • c# out causing a no overload for method error?
  • Which Thread resume the method execution after await in Asp.net Web application
  • How to open Asp.Net project in another computer
  • Azure app registrations - SQL Server permission for C# App
  • How to Submit String with 536000 Characters to API
  • Server side TcpClient's stream.read gets no data when a different client (connected to the same port) sends data
  • Add combo-box in windows form grid view by using LINQ query
  • Remove XLL addin when multiple XLL addins are installed
  • Deserialize dynamic json into generic .NET object
  • How to search node in Jobject
  • Iron Webscraper connects to host but doesn't scrape?
  • Change values from textbox at the touch of a button
  • Data access structure with Entity Framework
  • Link Assemblys failed unexpectedly (Xamarin.ios.dll)
  • ASP.NET Core Razor pages - not binding on POST Request
  • How to update appsettings.json from wix custom actions with the values passed as parameter during command line installat
  • Load undefined images from folders
  • How to add a new button in title bar next the minimize button in UWP?
  • Missing DLL in docker image after copying published tree inside
  • One of the identified items was in an invalid format
  • TLS1.2 does not exist with .NET v4.7
  • How do I parse a XML document into object models?
  • Why is a conditional style being set on a html element by Razor is always html encoded incorrectly
  • Counting the amount of repetitions a letter has in a string
  • How to get the encoding of a file in a repository git via C#?
  • Communication between an Azure web application and a windows form app on Azure VM
  • WCF Service - Client receiving CommunicationException after many requests to localhost
  • How to correctly view pdf in browser using DotVVM?
  • Reading part of json into c# object
  • YoutubeAPI v3 - Setting thumbnail returns Completed status, but no thumbnail is set on video
  • Using the SimpleInjector, is it possible to get a singleton by its implementation type?
  • Why the LogLevel rule is not set for my NLog?
  • Converting short? to TimeSpan
  • Publish build artifact through build.cake instead of Azure Devops
  • Unable to get new token using JWT method (C#)
  • Running HttpRequest synchronously C#
  • How to avoid format in "XDocument.Parse(strHtml)"
  • How to update naviation property with new values in EF Core?
  • Queued function not executing with dequeue
  • How to Control Sequence of columns automatically Generated in DataGrid
  • Getting error when try to add a file from library to main project?
  • Aggregate Roots DDD/UoW/Repo/Service
  • How to change the horizontal movement direction of the player in Unity2D?
  • Getting a two dimensional array of all possible unique combination of numbers lower than a mixmum for each cell starting
  • How to get LDAP nested groups from attribute
  • Get array consisting of first values of a list of tuples
  • How do I pass information from my View to my Controller as a Parameter
  • UWP BarcodeScanner Preview: CaptureElement doesn't show any Preview
  • How to register open generic with custom factory method?
  • Change image via in scriptable object in Unity
  • Decreasing value of one float when other go up
  • Xceed CheckComboBox not properly showing selected values from items hardcoded in XAML
  • Why does char array display contents on console while string and int arrays dont in c#?
  • How to prevent custom filters twice calls?
  • c#: remove brackets of certain size if existing including its content
  • Is there a simple way of handling nested Dictionary<string, object> types where object is either string or another
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org