C# Threading/Async: Running a task in the background while UI is interactable

前端 未结 4 1608

After looking around on both Async/Await and Threading, I\'m still unsure of the right way to apply it to my situation. No matter the variation that I try my UI still hangs

相关标签:
4条回答
  • 2020-12-05 07:42

    Instead of trying to use a bool for this, you should consider using the managed cancellation framework built into the framework.

    Basically, you'd build a CancellationTokenSource, and pass a CancellationToken to your method which could be used to handle cancellation.

    Finally, your current method will never get off the UI thread. You'd need to use Task.Run or similar to move the method to the ThreadPool if you don't want to block the UI.

    0 讨论(0)
  • 2020-12-05 07:56

    You've definitely implemented it incorrectly. You're returning a Task<int>, but only once all the work has already been done.

    It seems to me that you should probably just have a synchronous method:

    private static void MyFunction()
    {
        // Loop in here
    }
    

    Then start a task for it like this:

    Task task = Task.Run((Action) MyFunction);
    

    You can then await that task if you want - although in the example you've given, there's no point in doing so, as you're not doing anything after the await anyway.

    I'd also agree with Reed that using a CancellationToken would be cleaner than a static flag somewhere else.

    0 讨论(0)
  • 2020-12-05 07:57

    You did misunderstand.

    public static Task<int> myFunction()
    {
        //Stuff Happens
    
        while(StaticClass.stopFlag == false)
            //Do Stuff
    
        //Stuff Happens
    
        return Task.FromResult(1) //I know this is bad, part of the reason I'm asking
    }
    

    All of that code still happens in the intial await StaticClass.MyFunction(); call, it never returns control to the caller. What you need to do is put the loop portion in to a separate thread.

    public static async Task myFunction()
    {
        //Stuff Happens on the original UI thread
    
        await Task.Run(() => //This code runs on a new thread, control is returned to the caller on the UI thread.
        {
            while(StaticClass.stopFlag == false)
                //Do Stuff
        });
    
        //Stuff Happens on the original UI thread after the loop exits.
    }
    
    0 讨论(0)
  • 2020-12-05 08:06

    As an alternative, you could look into using BackgroundWorker class to do the job, your UI will stay interactive.

    0 讨论(0)
提交回复
热议问题