1. 程式人生 > >常見技術總結

常見技術總結

首先來看看.net的發展中的各個階段的特性:NET 與C# 的每個版本釋出都是有一個“主題”。即:C#1.0託管程式碼→C#2.0泛型→C#3.0LINQ→C#4.0動態語言→C#4.5非同步程式設計

  下面我來簡單的介紹一下非同步程式設計:非同步程式設計,在 .NET Framework 4.5 和 Windows 執行時利用非同步支援。 

  所謂的非同步程式設計是利用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);
        }
    }
}

二 .    設計模式

三.    通訊  

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.