Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
public static void Bar()
{
var context = SynchronizationContext.Current;
new Thread(delegate()
{
var requestA = HttpWebRequest.Create("http://ya.ru/");
var requestB = HttpWebRequest.Create("http://habr.ru/");
var futuresA = requestA.BeginGetResponse(delegate { }, null);
var futuresB = requestB.BeginGetResponse(delegate { }, null);
var resultA = requestA.EndGetResponse(futuresA);
var resultB = requestB.EndGetResponse(futuresB);
context.Post(delegate
{
Console.WriteLine(resultA.ContentType);
Console.WriteLine(resultB.ContentType);
}, null);
}).Start();
}Если не вдаваться в матан
Мы имеем штуку, которой действительно удобно пользоваться без боязни отстрелить себе ногу.
static void SyncVersion()
{
Stopwatch sw = Stopwatch.StartNew();
string[] urls = new string[]{"http://rsdn.ru", "http://gotdotnet.ru", "http://blogs.msdn.com"}
foreach (string url in urls)
{
DoDownload(url, ref sw)
}
}
void DoDownload(string url, ref Stopwatch sw)
{
var req = WebRequest.Create(url1);
var res = req.GetResponse();
Console.WriteLine("{0} : {1}, elapsed {2}ms", url, req.ContentLength, sw.ElapsedMilliseconds);
}
* This source code was highlighted with Source Code Highlighter.Во многом, Си – это ассемблер высокого уровня. Это даёт значительную гибкость и открывает ящик Пандоры с возможными ошибками.
Ограничение языка Си до определенного набора разрешенных конструкций не представляется возможным, так как получившийся язык не обладал бы нужной функциональностью.
Практически все конструкции языка придуманы, чтобы программист, в конце концов, прострелил себе ногу.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Downloader
{
class Program
{
private static readonly List<Utils.UrlExt> Urls =
new List<Utils.UrlExt>
{
new Utils.UrlExt(0, "http://ya.ru"),
new Utils.UrlExt(1, "http://google.ru"),
new Utils.UrlExt(2, "http://habrahabr.ru")
};
private static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("Press any key to start .... ");
Console.ReadKey();
Console.WriteLine(Environment.NewLine);
// ================== sync version ===================
sw.Restart();
Console.WriteLine("Starting Sync Version");
Console.WriteLine();
InnerDownloader.SyncDownload(Urls, sw);
Console.WriteLine("End Sync Version");
Console.WriteLine(Environment.NewLine);
// ================ end sync version =================
// ================== async rx version ===================
sw.Restart();
Console.WriteLine("Starting ASync RX (PFX) Version (.Net 3.5-4.0)");
Console.WriteLine();
InnerDownloader.RxASyncDownload(Urls, sw);
Console.WriteLine("End ASync RX (PFX) Version (.Net 3.5-4.0)");
Console.WriteLine(Environment.NewLine);
// ================ end async rx version =================
// ================== new async version ===================
sw.Restart();
Console.WriteLine("Starting New ASync Version (.Net 5.0)");
Console.WriteLine();
InnerDownloader.NewASyncDownload(Urls, sw);
Console.WriteLine("End New ASync Version (.Net 5.0)");
Console.WriteLine(Environment.NewLine);
// ================ end old async version =================
// ================== new async version v2 ===================
sw.Restart();
Console.WriteLine("Starting New ASync Version (.Net 5.0) v2");
Console.WriteLine();
InnerDownloader.NewASyncDownloadV2(Urls, sw);
Console.WriteLine("End New ASync Version (.Net 5.0) v2");
Console.WriteLine(Environment.NewLine);
// ================ end old async version v2 =================
// ================== new async version v3 ===================
sw.Restart();
Console.WriteLine("Starting New ASync Version (.Net 5.0) v3");
Console.WriteLine();
InnerDownloader.NewASyncDownloadV3(Urls, sw);
Console.WriteLine("End New ASync Version (.Net 5.0) v3");
Console.WriteLine(Environment.NewLine);
// ================ end old async version v3 =================
// ================== new async version v4 ===================
sw.Restart();
Console.WriteLine("Starting ASync RX (PFX) Version (.Net 3.5-4.0) + New ASync Version (.Net 5.0) v4");
Console.WriteLine();
InnerDownloader.NewASyncDownloadV4(Urls, sw);
Console.WriteLine("End ASync RX (PFX) Version (.Net 3.5-4.0) + New ASync Version (.Net 5.0) v4");
Console.WriteLine(Environment.NewLine);
// ================ end old async version v4 =================
Console.WriteLine("Press any key to exit .... ");
Console.ReadKey();
}
}
}
* This source code was highlighted with Source Code Highlighter.using System;
using System.IO;
using System.Net;
namespace Downloader
{
public class Utils
{
public static int GetLenght(WebResponse response)
{
string result = "";
var stream = response.GetResponseStream();
if (stream != null)
{
using (var sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result.Length;
}
public class UrlExt
{
public int Index;
public string Url;
internal UrlExt(int index, string url)
{
Index = index;
Url = url;
}
}
public static int DrawTextProgressBar(int progress, int total, string data)
{
progress = progress + 1;
//draw empty progress bar
Console.CursorLeft = 0;
Console.Write("["); //start
Console.CursorLeft = 12;
Console.Write("]"); //end
Console.CursorLeft = 1;
const float onechunk = 3.5F;
//draw filled part
int position = 1;
for (int i = 0; i < onechunk * progress; i++)
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.CursorLeft = position++;
Console.Write(" ");
}
//draw unfilled part
for (int i = position; i <= 11; i++)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.CursorLeft = position++;
Console.Write(" ");
}
//draw totals
Console.CursorLeft = 14;
Console.BackgroundColor = ConsoleColor.Black;
Console.Write("{0} of {1}, {2} ", progress, total, data); //blanks at the end remove any excess
Console.WriteLine(Environment.NewLine);
return 0;
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
namespace Downloader
{
/// <summary>
/// Синхронная версия
/// </summary>
public partial class InnerDownloader
{
public static void SyncDownload(List<Utils.UrlExt> urls, Stopwatch sw)
{
for (int index = 0; index < urls.Count; index++)
{
string result = DoSyncDownload(urls[index].Url, sw);
Utils.DrawTextProgressBar(index, urls.Count, result);
}
}
static string DoSyncDownload(string url, Stopwatch sw)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
var res = (HttpWebResponse)req.GetResponse();
return string.Format("{0}: {1}, {2}ms, Thread:{3}", url, Utils.GetLenght(res),
sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId);
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Downloader
{
/// <summary>
/// Версия для работы через Reactive, PFX
/// </summary>
public partial class InnerDownloader
{
public static void RxASyncDownload(List<Utils.UrlExt> urls, Stopwatch sw)
{
Parallel.For(0, urls.Count,
index =>
{
string result = DoSyncDownload(urls[index].Url, sw);
Utils.DrawTextProgressBar(index, urls.Count, result);
}
);
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Downloader
{
/// <summary>
/// Асинхронная версия стиль № 1
/// </summary>
public partial class InnerDownloader
{
public static async void NewASyncDownload(IEnumerable<Utils.UrlExt> urls, Stopwatch sw)
{
int count = urls.Count();
var tasks =
(
from url in urls
let result = DoASyncDownloadV1(url.Url)
select new
{
Response = result,
Output = Utils.DrawTextProgressBar
(
url.Index, count,
string.Format("{0}: {1}, {2}ms, Thread:{3}",
url.Url, Utils.GetLenght(result.Result),
sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId)
)
}
).ToList();
TaskEx.WhenAll(tasks.Select(t => t.Response));
}
static Task<WebResponse> DoASyncDownloadV1(string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
return req.GetResponseAsync();
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Downloader
{
/// <summary>
/// Асинхронная версия стиль № 2
/// </summary>
public partial class InnerDownloader
{
public static void NewASyncDownloadV2(List<Utils.UrlExt> urls, Stopwatch sw)
{
var task = InnerNewASyncDownloadV2(urls, sw);
task.Wait();
}
private static async Task InnerNewASyncDownloadV2(List<Utils.UrlExt> urls, Stopwatch sw)
{
int count = urls.Count();
for (int index = 0; index < count; index++)
{
var result = await DoASyncDownloadV2(urls[index].Url);
var data = string.Format("{0}: {1}, {2}ms, Thread:{3}",
urls[index].Url,
Utils.GetLenght(result),
sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
Utils.DrawTextProgressBar(index, urls.Count, data);
}
}
static Task<WebResponse> DoASyncDownloadV2(string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
return req.GetResponseAsync();
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Downloader
{
/// <summary>
/// Асинхронная версия стиль № 3
/// </summary>
public partial class InnerDownloader
{
public static void NewASyncDownloadV3(List<Utils.UrlExt> urls, Stopwatch sw)
{
for (int index = 0; index < urls.Count; index++)
{
string result = DoASyncDownloadV3(urls[index].Url, sw);
Utils.DrawTextProgressBar(index, urls.Count, result);
}
}
private static string DoASyncDownloadV3(string url, Stopwatch sw)
{
List<string> output = new List<string> { "" };
var response = InnerNewASyncDownloadV3(url, sw, output);
response.Wait();
return output[0];
}
private static async Task InnerNewASyncDownloadV3(string url, Stopwatch sw, IList<string> output)
{
var result = await DoASyncDownloadV3(url);
output[0] = string.Format("{0}: {1}, {2}ms, Thread:{3}",
url,
Utils.GetLenght(result),
sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
}
static Task<WebResponse> DoASyncDownloadV3(string url)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
return req.GetResponseAsync();
}
}
}
* This source code was highlighted with Source Code Highlighter.using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Downloader
{
/// <summary>
/// Асинхронная версия 3 + PFX
/// </summary>
public partial class InnerDownloader
{
public static void NewASyncDownloadV4(List<Utils.UrlExt> urls, Stopwatch sw)
{
Parallel.For(0, urls.Count,
index =>
{
string result = DoASyncDownloadV3(urls[index].Url, sw);
Utils.DrawTextProgressBar(index, urls.Count, result);
}
);
}
}
}
* This source code was highlighted with Source Code Highlighter.
Знакомство с асинхронными операциями в C# 5