zoukankan      html  css  js  c++  java
  • ASP.NET Learning Center---学习ASP.NET(1)

    1,学习地址---微软官网

    2,目标:学习Razor,以及建立Web应用.

    image

    3,https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/?view=aspnetcore-3.0

    4,概念学习:

    异步编程模型 (TAP)'

    相关网站

    https://www.cnblogs.com/neverc/p/4653539.html

    5, 异步线程执行的几个方式:

       1,创建任务并且启动:

    //方法1:
    Task t = new Task(
                   () =>
                   {
                       Thread.Sleep(1000);
                       Console.WriteLine("Hello,World1
    ");
                   });
                 t.Start();
    //方法2:
    await Task.Run(
                 () =>
                 {
                     Thread.Sleep(1000);
                     Console.WriteLine("Hello,World1
    ");
                 });
    //方法3:
    Task<string> task2 =Task.Factory.StartNew<string>(() =>
                {
                    return $"hello, task2的ID为{ Thread.CurrentThread.ManagedThreadId}";
                });

    2,aysnc 和 await的组合:

    Thread.Sleep(1000);
                 Console.WriteLine("Hello,World ");
                  await Task.Run<int>(
                  () =>
                  {
                      Thread.Sleep(1000);
                      Console.WriteLine("Hello,World1 ");
                      return 1;
                  });
                 Console.WriteLine("Hello,World2 ");
                 return 1;

    注意: 执行顺序     主函数---->调用aysnc函数并执行到await语句---------->回到主程序--->执行await之后的语句.

                                                                                                                      /

                                                              --执行 异步函数体-----------并且返回----/

    3,任务的启动,取消,回调等...

    任务等待:

    Task的Wait/WaitAny/WaitAll方法
    Task.WaitAll(new Task[]{ task1,task2});
    Task.Factory.ContinueWhenAll(new Task[] { task1, task2 }, (t) =>
                {
                    Thread.Sleep(100);
                    Console.WriteLine("执行后续操作");
                });

    4,任务取消CancellationTokenSource

    namespace CancelAListOfTasks
    {
        public partial class MainWindow : Window
        {
            // Declare a System.Threading.CancellationTokenSource.
            CancellationTokenSource cts;
    
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private async void startButton_Click(object sender, RoutedEventArgs e)
            {
                // Instantiate the CancellationTokenSource.
                cts = new CancellationTokenSource();
    
                resultsTextBox.Clear();
    
               try
                {
                    await AccessTheWebAsync(cts.Token);
                    // ***Small change in the display lines.
                    resultsTextBox.Text += "
    Downloads complete.";
                }
                catch (OperationCanceledException)
                {
                    resultsTextBox.Text += "
    Downloads canceled.";
                }
                catch (Exception)
                {
                    resultsTextBox.Text += "
    Downloads failed.";
                }
    
                // Set the CancellationTokenSource to null when the download is complete.
                cts = null;
            }
    
            // Add an event handler for the Cancel button.
            private void cancelButton_Click(object sender, RoutedEventArgs e)
            {
                if (cts != null)
                {
                    cts.Cancel();
                }
            }
    
            // Provide a parameter for the CancellationToken.
            // ***Change the return type to Task because the method has no return statement.
            async Task AccessTheWebAsync(CancellationToken ct)
            {
                // Declare an HttpClient object.
                HttpClient client = new HttpClient();
    
                // ***Call SetUpURLList to make a list of web addresses.
                List<string> urlList = SetUpURLList();
    
                // ***Add a loop to process the list of web addresses.
                foreach (var url in urlList)
                {
                    // GetAsync returns a Task<HttpResponseMessage>.
                    // Argument ct carries the message if the Cancel button is chosen.
                    // ***Note that the Cancel button can cancel all remaining downloads.
                    HttpResponseMessage response = await client.GetAsync(url, ct);
    
                    // Retrieve the website contents from the HttpResponseMessage.
                    byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
    
                    resultsTextBox.Text +=
                        $"
    Length of the downloaded string: {urlContents.Length}.
    ";
                }
            }
    
            // ***Add a method that creates a list of web addresses.
            private List<string> SetUpURLList()
            {
                List<string> urls = new List<string>
                {
                    "https://msdn.microsoft.com",
                    "https://msdn.microsoft.com/library/hh290138.aspx",
                    "https://msdn.microsoft.com/library/hh290140.aspx",
                    "https://msdn.microsoft.com/library/dd470362.aspx",
                    "https://msdn.microsoft.com/library/aa578028.aspx",
                    "https://msdn.microsoft.com/library/ms404677.aspx",
                    "https://msdn.microsoft.com/library/ff730837.aspx"
                };
                return urls;
            }
        }
    static async void GetWebAsync1(CancellationToken ct)
            {
                try
                {
                    await AccessTheWebAsync(ct);
    
                }
                catch (OperationCanceledException)
                {
    
                }
                catch (Exception)
                {
    
    
    
                }
    
            }
        }

    5 在一个任务完成后取消后续任务

    static async Task  AccessTheWebAsync(CancellationTokenSource cts,CancellationToken ct)
            {
                HttpClient client = new HttpClient();
                List<string> urlList = SetUpURLList();
                IEnumerable<Task<int>> downloadTasksQuery =
                    from url in urlList select ProcessURLAsync(url, client, ct);
    
                // ***Use ToArray to execute the query and start the download tasks.   
                Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
    
                // ***Call WhenAny and then await the result. The task that finishes   
                // first is assigned to firstFinishedTask.  
                Task<int> firstFinishedTask = await Task.WhenAny(downloadTasks);
                
    cts.Cancel();
                // websites can finish first.  
                var length = await firstFinishedTask;
                Console.WriteLine($"
    Length of the downloaded website:  {length}
    ");
            }

    5.1 利用 Linq语法生成枚举类型,然后再触发异步事件群.

    5.2 利用WhenAny,WhenAll等方法进行堵塞

    static async Task  AccessTheWebAsync(CancellationTokenSource cts,CancellationToken ct)
            {
                HttpClient client = new HttpClient();
                List<string> urlList = SetUpURLList();
                IEnumerable<Task<int>> downloadTasksQuery =
                    from url in urlList select ProcessURLAsync(url, client, ct);
    
                // ***Use ToArray to execute the query and start the download tasks.   
                Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
               int[] first =await Task.WhenAll(downloadTasks);
                foreach(var x in first) Console.WriteLine(x + "
    ");
    
            }
           static async Task<int> ProcessURLAsync(string url, HttpClient client, CancellationToken ct)
            {
                // GetAsync returns a Task<HttpResponseMessage>.   
                HttpResponseMessage response = await client.GetAsync(url, ct);
    
                // Retrieve the website contents from the HttpResponseMessage.  
                byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
                Console.WriteLine("
    {urlContents}");
                return urlContents.Length;
            }

    6,异步的防止再次进入函数的方法:

  • 相关阅读:
    生成微博授权URL及回调地址
    微博三方登录
    celery异步发送短信
    celery配置
    celery原理与组件
    Django----短信验证接口
    Django----图片验证码接口
    编写注册接口
    jwt安装配置
    day19-Exception
  • 原文地址:https://www.cnblogs.com/frogkiller/p/12214456.html
Copyright © 2011-2022 走看看