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

前端 未结 4 1611

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:57

    You did misunderstand.

    public static Task 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.
    }
    

提交回复
热议问题