Home > Net >  I can't Task async and return bool
I can't Task async and return bool

Time:07-30

Is there any way to convert the Task to a Task async or something similar? I'm testing code, in short learning to perform different functions of Task type and learn to use its correct operation, however I have not been able to solve this "problem", so I want to ask people who have more knowledge about the Tasks.

Task<bool>.Factory.StartNew(() => {}); -> Task<bool>.Factory.StartNew(async () => {});

Here is a summary of what I want to do

    private bool completed = false;

    void Tester()
    {
        completed = false;
        int iteration = 0;
        var log = new Logger();
        log.Log(Logger.Level.Debug, "Starting");
        try
        {
            var theTask = Task<bool>.Factory.StartNew( () =>
            {
                while (!completed)
                {
                    log.Log(Logger.Level.Debug, "Waiting",1);
                    iteration  ;
                    Thread.Sleep(400);
                    if (iteration>20)
                    {
                        completed = true;
                        return true;
                    }
                }

                return false;
            }).Result;
        }
        catch (Exception e)
        {
            log.Log(Logger.Level.Error, e.ToString());
        }
        finally
        {
          log.Log(Logger.Level.Info, "Completed");  
        }
    }

CodePudding user response:

You can do it. You can see this video to understand async/await pattern: https://www.youtube.com/watch?v=il9gl8MH17s.

Try this:

class Program
    {
        static async Task Main(string[] args)
        {
            bool result = await Tester();
            System.Diagnostics.Debug.WriteLine($"result: {result}");
           
        }

        private static bool completed = false;

        static async Task<bool> Tester()
        {
            completed = false;
            int iteration = 0;
            //var log = new Logger();
            //log.Log(Logger.Level.Debug, "Starting");
            try
            {
                await  Task.Factory.StartNew(() =>
                {
                    while (!completed)
                    {
                        //log.Log(Logger.Level.Debug, "Waiting", 1);
                        iteration  ;
                        System.Diagnostics.Debug.WriteLine($"iteration {iteration}");
                        Task.Delay(2000);
                        if (iteration > 20)
                        {
                            completed = true;
                        }
                    }
                });
            }
            catch (Exception e)
            {
                //log.Log(Logger.Level.Error, e.ToString());
            }
            finally
            {
                //log.Log(Logger.Level.Info, "Completed");
            }
            return completed;
        }
    }
  • Related