Use VS2017 C# 7.0 to accelerate async code
来源:互联网 发布:linux内核编译详解 编辑:程序博客网 时间:2024/06/05 03:37
Reference:
http://www.debug.is/2015/04/17/c-sharp-vs-go/
http://www.jb51.net/article/108159.htm
Before VS2017 C# 7:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
namespace newfeature
{
public class CacheContext
{
public static async Task<List<DownloadResult>> DownloadUrlsAsync(string path)
{
var results = new List<DownloadResult>();
List<Task<DownloadResult>> tasks = File.ReadLines(path).Select(a =>
DownloadAsync(a)).ToList();
while (tasks.Any())
{
Task<DownloadResult> task = await Task.WhenAny(tasks);
tasks.Remove(task);
results.Add(task.Result);
}
return results;
}
private static async Task<DownloadResult> DownloadAsync(string url)
{
try
{
//using (System.Net.WebClient client = new WebClient())
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// byte[] data = await client.DownloadDataTaskAsync(new Uri(url));
byte[] data = new byte[10];
await Task.Delay(5000);
stopwatch.Stop();
return new DownloadResult()
{
Url = url,
Time = stopwatch.ElapsedMilliseconds,
Success = true,
SizeInBytes = data.Length
};
}
}
catch (Exception x)
{
Console.WriteLine("error downloading {0}: {1}", url, x);
return new DownloadResult()
{
Url = url,
Time = int.MaxValue,
SizeInBytes = 0,
Success = false
};
}
}
}
public class DownloadResult
{
public string Url { get; set; }
public long Time { get; set; }
public bool Success { get; set; }
public int SizeInBytes { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<DownloadResult> result = null;
Action act = async () =>
{
result = await CacheContext.DownloadUrlsAsync(args[0]);
if (result != null)
{
foreach (DownloadResult r in result)
{
Console.WriteLine(r.Time + " " + r.Url);
}
}
result = await CacheContext.DownloadUrlsAsync(args[0]);
if (result != null)
{
foreach (DownloadResult r in result)
{
Console.WriteLine(r.Time + " " + r.Url);
}
}
};
act();
Console.Read();
}
}
}
After VS2017 C# 7.0:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
namespace newfeature
{
public class CacheContext
{
private static Dictionary<string, DownloadResult> cache = new Dictionary<string, DownloadResult>();
public static async Task<List<DownloadResult>> DownloadUrlsAsync(string path)
{
var results = new List<DownloadResult>();
List<Task<DownloadResult>> tasks = File.ReadLines(path).Select(a =>
CachedDownloadAsync(a).AsTask()).ToList();
while (tasks.Any())
{
Task<DownloadResult> task = await Task.WhenAny(tasks);
tasks.Remove(task);
results.Add(task.Result);
}
return results;
}
private static ValueTask<DownloadResult> CachedDownloadAsync(string url)
{
lock (cache)
{
return cache.ContainsKey(url) ? new ValueTask<DownloadResult>(cache[url]): new ValueTask<DownloadResult> (DownloadAsync(url));
}
}
private static async Task<DownloadResult> DownloadAsync(string url)
{
try
{
//using (System.Net.WebClient client = new WebClient())
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// byte[] data = await client.DownloadDataTaskAsync(new Uri(url));
byte[] data = new byte[10];
await Task.Delay(5000);
stopwatch.Stop();
DownloadResult result = new DownloadResult()
{
Url = url,
Time = stopwatch.ElapsedMilliseconds,
Success = true,
SizeInBytes = data.Length
};
lock (cache)
{
cache[url] = result;
}
return result;
}
}
catch (Exception x)
{
Console.WriteLine("error downloading {0}: {1}", url, x);
return new DownloadResult()
{
Url = url,
Time = int.MaxValue,
SizeInBytes = 0,
Success = false
};
}
}
}
public class DownloadResult
{
public string Url { get; set; }
public long Time { get; set; }
public bool Success { get; set; }
public int SizeInBytes { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<DownloadResult> result = null;
Action act = async () =>
{
result = await CacheContext.DownloadUrlsAsync(args[0]);
if (result != null)
{
foreach (DownloadResult r in result)
{
Console.WriteLine(r.Time + " " + r.Url);
}
}
result = await CacheContext.DownloadUrlsAsync(args[0]);
if (result != null)
{
foreach (DownloadResult r in result)
{
Console.WriteLine(r.Time + " " + r.Url);
}
}
};
act();
Console.Read();
}
}
}
- Use VS2017 C# 7.0 to accelerate async code
- use make_immutable to accelerate your Class Moose
- Use .NET SocketAsyncEventArgs to write socket server code in C#
- Impersonate: use specified credential to execute some code in C#
- About how to use Async Task interesting
- Use code to approve SPListItem
- C# frequently use code snippet
- Node.js async in practice: When to use what?
- NodeJS async实例详解:When to use what?
- Node.js async in practice: When to use what?
- Use SVN to manage your code
- use code to add Navigation----iphone
- Use gprof to visualize code running time
- How to use C# controls
- [转] C#7.0新特性(VS2017可用)
- [转] C#7.0新特性(VS2017可用)
- how to use Task to represent the old Begin/End async methods
- How to use log4net in C# application
- linux下如何安装jdk
- DeepLearning&Keras学习笔记3__mnist数据集CNN
- 一款有趣的游戏
- 53. Maximum Subarray
- JavaScript权威指南读书笔记——第七章 数组
- Use VS2017 C# 7.0 to accelerate async code
- 关于HTML form accept-charset 属性的若干尝试
- 处理阶乘及阶乘逆元的小技巧
- ImageLoader 图片加载框架
- 递归与动态规划---汉诺塔问题
- centos7安装ansible遇到的问题
- 金蝶K3 SQL报表系列-库存账龄分析
- 1003. 我要通过!(20)
- 计算机中叉积