美文网首页
C# Async Await用法演示的代码

C# Async Await用法演示的代码

作者: 程序媛宝 | 来源:发表于2018-12-18 14:33 被阅读0次

    如下的代码是关于C# Async Await用法演示的代码,希望对码农也有用处。

    public void Main()

    {

        var result = LaunchTasks(new List<int>() { 5, 3 });

        Debug.WriteLine("The final result is {0}",result.Result);

    }

    public async Task<bool> LaunchTasks(List<int> waitTimes)

    {

        bool result = false;

        List<Task> tasks = new List<Task>();

        try

        {

          foreach (int wait in waitTimes)

          {

              var task1 = FirstWait(wait);

              tasks.Add(task1);

              var task2 = SecondWait(wait);

              tasks.Add(task2);

          }

          Debug.WriteLine("About to await on {0} Tasks", tasks.Count);

          await Task.WhenAll(tasks);

          Debug.WriteLine("After WhenAll");

        }

        catch (Exception ex)

        {

        }

        return result;

    }

    private async Task<bool> FirstWait(int waitTime)

    {

        var task = Task.Factory.StartNew<bool>((delay) =>

        {

            try

            {

                int count = (int)delay;

                for (int i = 0; i < count; i++)

                {

                    Debug.WriteLine("FirstWait is at {0}", i);

                }

            }

            catch (Exception ex)

            {

                Debug.WriteLine(ex.Message);

            }

            return true;

        }, waitTime);

        await Task.WhenAll(task);

        Debug.WriteLine("After FirstWait");

        return task.Result;

    }

    private async Task<bool> SecondWait(int waitTime)

    {

        var task = Task.Factory.StartNew<bool>((delay) =>

        {

            try

            {

                int count = (int)delay;

                for (int i = 0; i < count; i++)

                {

                    Debug.WriteLine("SecondWait is at {0}", i);

                }

            }

            catch (Exception ex)

            {

                Debug.WriteLine(ex.Message);

            }

            return true;

        }, waitTime);

        await Task.WhenAll(task);

        Debug.WriteLine("After SecondWait");

        return task.Result;

    }

    相关文章

      网友评论

          本文标题:C# Async Await用法演示的代码

          本文链接:https://www.haomeiwen.com/subject/znqlkqtx.html