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

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

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\n");
});
t.Start();
//方法2:
await Task.Run(
() =>
{
Thread.Sleep(1000);
Console.WriteLine("Hello,World1\n");
});
//方法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\n");
              await Task.Run<int>(
              () =>
              {
                  Thread.Sleep(1000);
                  Console.WriteLine("Hello,World1\n");
                  return 1;
              });
             Console.WriteLine("Hello,World2\n");
             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 += "\r\nDownloads complete.";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads 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 +=
$"\r\nLength of the downloaded string: {urlContents.Length}.\r\n";
}
} // ***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($"\r\nLength of the downloaded website: {length}\r\n");
}

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 + "\r\n"); }
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("\r\n{urlContents}");
return urlContents.Length;
}

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

ASP.NET Learning Center---学习ASP.NET(1)的更多相关文章

  1. ASP.NET 开发者 开始学习ASP.NET Core 2吧

    .  NET Core 从2016年6月28日发布,过去了将近一年的时间,但是在工作中发现大家对.net core的接受程度并不高,这只是一个感觉,俗话说“没有调查就没有发言权”, 这两天通过微信小程 ...

  2. 学习ASP.NET MVC(九)——“Code First Migrations ”工具使用示例

    在上一篇文章中,我们学习了如何使用实体框架的“Code First Migrations ”工具,使用其中的“迁移”功能对模型类进行一些修改,同时同步更新对应数据库的表结构. 在本文章中,我们将使用“ ...

  3. 学习ASP.NET MVC(七)——我的第一个ASP.NET MVC 查询页面

    在本篇文章中,我将添加一个新的查询页面(SearchIndex),可以按书籍的种类或名称来进行查询.这个新页面的网址是http://localhost:36878/Book/ SearchIndex. ...

  4. 学习ASP.NET MVC(一)——我的第一个ASP.NET MVC应用程序

    学习ASP.NET MVC系列: 学习ASP.NET MVC(一)——我的第一个ASP.NET MVC应用程序 学习ASP.NET MVC(二)——我的第一个ASP.NET MVC 控制器 学习ASP ...

  5. 学习ASP.NET MVC(十一)——分页

    在这一篇文章中,我们将学习如何在MVC页面中实现分页的方法.分页功能是一个非常实用,常用的功能,当数据量过多的时候,必然要使用分页.在今天这篇文章中,我们学习如果在MVC页面中使用PagedList. ...

  6. 学习ASP.NET MVC系列 - 还有比这更简炼的吗?把复杂的事情变简单了,贡献啊!

    转自

  7. Asp.NET之对象学习

    一.总述 二.具体介绍 1.Request对象 Request对象是用来获取client在请求一个页面或传送一个Form时提供的全部信息,这包含可以标识浏览器和用户的HTTP变量,存储在client的 ...

  8. 学习ASP.NET Core,你必须了解无处不在的“依赖注入”

    ASP.NET Core的核心是通过一个Server和若干注册的Middleware构成的管道,不论是管道自身的构建,还是Server和Middleware自身的实现,以及构建在这个管道的应用,都需要 ...

  9. ASP.Net WebForm温故知新学习笔记:一、aspx与服务器控件探秘

    开篇:毫无疑问,ASP.Net WebForm是微软推出的一个跨时代的Web开发模式,它将WinForm开发模式的快捷便利的优点移植到了Web开发上,我们只要学会三步:拖控件→设属性→绑事件,便可以行 ...

随机推荐

  1. HBase学习总结

    一.HBase介绍 1.基本概念 HBase是一种Hadoop数据库,经常被描述为一种稀疏的,分布式的,持久化的,多维有序映射,它基于行键.列键和时间戳建立索引,是一个可以随机访问的存储和检索数据的平 ...

  2. show processlist详解

    摘自:https://blog.csdn.net/sunqingzhong44/article/details/70570728?utm_source=copy 如果您有root权限,您可以看到所有线 ...

  3. js的三种输出语句,以及html的运行循序

    js最常见的三种输出语句 1.console.log()这个语句是在浏览器控制台输出的.进入网页点击f12可查看 2.alert()弹出一个对话框, 3.document.write这个语句是在页面输 ...

  4. vue简介,插值表达式,过滤器

    目录 VUE框架介绍 what?什么是vue? why?为什么要学习vue? special特点? how如何使用? 下载安装? 导入方式? 挂在点el 插值表达式 delimiters自定义插值表达 ...

  5. 【搞定面试官】- Synchronized如何实现同步?锁优化?(1)

    前言 说起Java面试中最高频的知识点非多线程莫属.每每提起多线程都绕不过一个Java关键字--synchronized.我们都知道该关键字可以保证在同一时刻,只有一个线程可以执行某个方法或者某个代码 ...

  6. 目标检测之单步检测(Single Shot detectors)

    目标检测之单步检测(Single Shot detectors) 前言 像RCNN,fast RCNN,faster RCNN,这类检测方法都需要先通过一些方法得到候选区域,然后对这些候选区使用高质量 ...

  7. DBA常用SQL之DDL生成语句-2

    ------数据迁移常用SQL SELECT 'DROP USER '||u.username ||' CASCADE;' AS dropstrs FROM DBA_USERS U where u.u ...

  8. Uncaught Error: Call to undefined function mcrypt_get_iv_size() 解决办法

    函数 mcrypt_get_iv_size 在只在(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) 这几个版本 ...

  9. 《Head first设计模式》学习笔记

    1. 单例模式 2. 工厂模式 3. 抽象工厂 4. 策略模式 5. 观察者模式 6. 装饰者模式 7. 命令模式 8. 适配器模式 9. 外观模式 10. 模版方法模式 11. 迭代器模式 设计模式 ...

  10. ceph集群部署

    最近在学习 kubernetes 过程中,想实现 pod 数据的持久化.在调研的过程中,发现 ceph 在最近几年发展火热,也有很多案例落地企业.在选型方面,个人更加倾向于社区火热的项目,Gluste ...