常见技术总结

一.  异步  ---转自 https://www.cnblogs.com/HJL-Blog/p/4432632.html


首先来看看.net的发展中的各个阶段的特性:NET 与C# 的每个版本发布都是有一个“主题”。即:C#1.0托管代码→C#2.0泛型→C#3.0LINQ→C#4.0动态语言→C#4.5异步编程

  下面我来简单的介绍一下异步编程:异步编程,在 .NET Framework 4.5 和 Windows 运行时利用异步支持。 编译器可执行开发人员曾进行的高难度工作,且应用程序保留了一个类似于同步代码的逻辑结构。 因此,你只需做一小部分工作就可以获得异步编程的所有好处。(https://msdn.microsoft.com/zh-cn/library/hh191443.aspx

  所谓的异步编程是利用CPU空闲时间和多核的特性,它所返回的Task或Task<TResult>是对await的一个承诺,当任务执行完毕后返回一个结果给接收者。这里看到这个可能各位不太明白,不要紧,下面会有讲解。

使用场景: 对结果顺序无要求的, 要同时处理多任务的

效率: 高

结果 : 多线程竞争的问题


方法的返回类型是Task /Task<TResult>       调用方法和方法前都需要加 await    /*方法名称后缀一般有Async*/ async key word

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

namespace 异步递归
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            ConsoleAsync1();
            stopwatch.Stop();
            Console.WriteLine("同步方法用时:" + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();
            stopwatch.Start();
            ConsoleAsync();
            stopwatch.Stop();
            Console.WriteLine("异步方法用时:"+ stopwatch.ElapsedMilliseconds);

            Console.Read();
        }

        private static async void ConsoleAsync()
        {
            Console.WriteLine("异步方法开始");
            Console.WriteLine("Result:" + await SumAsync(10));
            Console.WriteLine("异步方法结束");
        }
        private static async Task<int> SumAsync(int part)
        {
            if ((part += 10) >= 100)
            {
                return 100;
            }
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
            Console.WriteLine(DateTime.Now.Millisecond + " 异步 " + (await getStringTask).Length);
            return await SumAsync(part);
        }

        private static void ConsoleAsync1()
        {
            Console.WriteLine("同步方法开始");
            Console.WriteLine("Result:" + SumAsync1(10));
            Console.WriteLine("同步方法结束");
        }

        private static int SumAsync1(int part)
        {
            if ((part += 10) >= 100)
            {
                return 100;
            }
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
            Console.WriteLine(DateTime.Now.Millisecond + " 同步 " + getStringTask.Result.Length);
            return SumAsync1(part);
        }
    }
}

二 .    设计模式

三.    通信  

 WCF ,Web API--自动创建web api的说明


Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application. This tutorial walks you through the steps.
Overview
To use Web API in a Web Forms application, there are two main steps:
Add a Web API controller that derives from the ApiController class.
Add a route table to the Application_Start method.
Create a Web Forms Project
Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Forms Application. Enter a name for the project and click OK.

Create the Model and Controller
This tutorial uses the same model and controller classes as the Getting Started tutorial.
First, add a model class. In Solution Explorer, right-click the project and select Add Class. Name the class Product, and add the following implementation:
C#

Copy
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}
Next, add a Web API controller to the project., A controller is the object that handles HTTP requests for Web API.
In Solution Explorer, right-click the project. Select Add New Item.

Under Installed Templates, expand Visual C# and select Web. Then, from the list of templates, select Web API Controller Class. Name the controller "ProductsController" and click Add.

The Add New Item wizard will create a file named ProductsController.cs. Delete the methods that the wizard included and add the following methods:
C#

Copy
namespace WebForms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    public class ProductsController : ApiController
    {

        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(
                (p) => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}
For more information about the code in this controller, see the Getting Started tutorial.
Add Routing Information
Next, we'll add a URI route so that URIs of the form "/api/products/" are routed to the controller.
In Solution Explorer, double-click Global.asax to open the code-behind file Global.asax.cs. Add the following using statement.
C#

Copy
using System.Web.Http;
Then add the following code to the Application_Start method:
C#

Copy
RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
For more information about routing tables, see Routing in ASP.NET Web API.
Add Client-Side AJAX
That's all you need to create a web API that clients can access. Now let's add an HTML page that uses jQuery to call the API.
Make sure your master page (for example, Site.Master) includes a ContentPlaceHolder with ID="HeadContent":
HTML

Copy
<asp:ContentPlaceHolder runat="server" ID="HeadContent"></asp:ContentPlaceHolder>
Open the file Default.aspx. Replace the boilerplate text that is in the main content section, as shown:
aspx

Copy
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>Products</h2>
    <table>
    <thead>
        <tr><th>Name</th><th>Price</th></tr>
    </thead>
    <tbody id="products">
    </tbody>
    </table>
</asp:Content>
Next, add a reference to the jQuery source file in the HeaderContent section:
aspx

Copy
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</asp:Content>
Note: You can easily add the script reference by dragging and dropping the file from Solution Explorer into the code editor window.

Below the jQuery script tag, add the following script block:
HTML

Copy
<script type="text/javascript">
    function getProducts() {
        $.getJSON("api/products",
            function (data) {
                $('#products').empty(); // Clear the table body.

                // Loop through the list of products.
                $.each(data, function (key, val) {
                    // Add a table row for the product.
                    var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
                    $('<tr/>', { html: row })  // Append the name.
                        .appendTo($('#products'));
                });
            });
        }

        $(document).ready(getProducts);
</script>
When the document loads, this script makes an AJAX request to "api/products". The request returns a list of products in JSON format. The script adds the product information to the HTML table.
When you run the application, it should look like this:

Note
The feedback system for this content will be changing soon. Old comments will not be carried over. If content within a comment thread is important to you, please save a copy. For more information on the upcoming change, we invite you to read our blog post.


猜你喜欢

转载自blog.csdn.net/softuse/article/details/80909148