C#5.0 .net 4.5示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
//filename: MathOperations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestAsyncAwait
{
    public class MathOperations
    {
        public static double MultiplyByTwo(double d)
        {
            return d * 2;
        }
 
        public static double Square(double d)
        {
            return d * d;
        }
 
    }
}
 
 
//filename: MyClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace TestAsyncAwait
{
    public class MyClass
    {
        public MyClass()
        {
            //DisplayValue();
            DisplayValueWithContinuationTask();
            Console.WriteLine("MyClass() end.");
        }
 
        public Task<double> GetValueAsync(double num1, double num2)
        {
            return Task.Run<double>(() => {
                Thread.Sleep(1000);
                return num1 + num2;
            });
        }
 
        public async void DisplayValue()
        {
            double result = await GetValueAsync(1, 2);
            Console.WriteLine("result is :" + result);
        }
 
        public void DisplayValueWithContinuationTask()
        {
            Task<double> task = GetValueAsync(1, 2);
            task.ContinueWith(t =>
            {
                double result = t.Result;
                Console.WriteLine("result is :" + result);
            });
        }
 
 
    }
}
 
 
//filename: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace TestAsyncAwait
{
    class Program
    {
        public static Tuple<int, int> Divide(int dividend, int divisor)
        {
            int result = dividend / divisor;
            int reminder = dividend % divisor;
            return Tuple.Create<int, int>(result, reminder);
        }
 
        private delegate string GetAString();
 
        static void ProcessAndDispalyNumber(Func<double,double> action,  double value){
            double result = action(value);
            Console.WriteLine(string.Format("value={0},result={1}", value, result));
        }
 
        #region 异步编程实验
 
        static string Greeting(string name)
        {
            Thread.Sleep(3000);
            return string.Format("threadID:[{0}] says: Hello, {1}!", Thread.CurrentThread.ManagedThreadId, name);
        }
 
        static Task<string> GreetingAsync(string name)
        {
            return Task.Run<string>(() => {
                return Greeting(name);
            });
        }
 
        async static void CallerWithAsync()
        {
            string result = await GreetingAsync("张三");
            Console.WriteLine(result);
        }
 
        static void CallerWithContinuationWith()
        {
            Task<string> task = GreetingAsync("张三");
            task.ContinueWith(t => {
                string result = t.Result;
                Console.WriteLine(result);
            });
        }
 
        async static void MultipleAsyncMethods()
        {
            string result1 = await GreetingAsync("张三@");
            string result2 = await GreetingAsync("李四@");
            Console.WriteLine("Finished with 2 result: {0},{1}", result1, result2);
        }
 
        async static void MultipleAsyncMethodsWithCombinators1()
        {
            Task<string> t1 =  GreetingAsync("张三1");
            Task<string> t2 =  GreetingAsync("李四1");
            await Task.WhenAll(t1, t2);
            Console.WriteLine("Finished with 2 result: {0},{1}", t1.Result, t2.Result);
        }
 
        async static void MultipleAsyncMethodsWithCombinators2()
        {
            Task<string> t1 = GreetingAsync("张三2");
            Task<string> t2 = GreetingAsync("李四2");
            string[] result = await Task.WhenAll(t1, t2);
            Console.WriteLine("Finished with 2 result: {0},{1}", result[0], result[1]);
        }
 
        #endregion
 
        static void Main(string[] args)
        {
            /*
            CallerWithAsync();
            CallerWithContinuationWith();
            MultipleAsyncMethods();
            MultipleAsyncMethodsWithCombinators1();
            MultipleAsyncMethodsWithCombinators2();
 
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Done.");
            */
            ParallelLoopResult result = Parallel.For(0, 10, async i => {
                Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId,
                    Thread.CurrentThread.ManagedThreadId);
                //Thread.Sleep(10);
                await Task.Delay(10);
                Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId,
                    Thread.CurrentThread.ManagedThreadId);
            });
            Console.WriteLine("Is completed: {0}", result.IsCompleted);
 
 
            /*
            MyClass mc = new MyClass();
 
            Console.WriteLine("-----------------");
 
            var result = Divide(5, 2);
            Console.WriteLine(string.Format("result={0},reminder={1}",result.Item1, result.Item2));
 
            int x = 4;
            //GetAString func = new GetAString(x.ToString);
            GetAString func = x.ToString;
            Console.WriteLine(func());
            Console.WriteLine(func.Invoke());
 
            Func<double, double>[] operations =
            {
                MathOperations.MultiplyByTwo,
                MathOperations.Square
            };
            foreach (var item in operations)
            {
                ProcessAndDispalyNumber(item, 3.14);
            }
 
            string midPart = ", middle part,";
            Func<string, string> anonDel = delegate(string value) {
                string s = value + midPart;
                s += " last part";
                return s;
            };
            Console.WriteLine(anonDel("Hello"));
 
            Func<string, string> anonDel2 = (string value) =>
            {
                string s = value + midPart;
                s += " last part. version 2";
                return s;
            };
            Console.WriteLine(anonDel2("Hello"));
 
            Func<string, string> anonDel3 = value =>
            {
                string s = value + midPart;
                s += " last part. version 3";
                return s;
            };
            Console.WriteLine(anonDel3("Hello"));
 
            int someValue = 5;
            Func<int, int> f = p1 => p1 + someValue;
            Console.WriteLine(f(1));
            someValue = 6;
            Console.WriteLine(f(1));
            //var lists = new List<string>() { "1","2"};
 
            dynamic dyn;
            dyn = 100;
            Console.WriteLine(dyn.GetType());
            Console.WriteLine(dyn);
 
            dyn = "abc中国";
            Console.WriteLine(dyn.GetType());
            Console.WriteLine(dyn);
           */
            Console.ReadKey();
        }
    }
}

 

posted @   庚武  Views(649)  Comments(0Edit  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示