Skip to content

Instantly share code, notes, and snippets.

@ToJans
Created June 14, 2012 12:10
Show Gist options
  • Save ToJans/2929935 to your computer and use it in GitHub Desktop.
Save ToJans/2929935 to your computer and use it in GitHub Desktop.
Testing difference between sync and async
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
// result
//10 11 13 15 17 19 3 5 7 9 12 4 2 6 8 14 16 0 18 1
//0 2 4 12 10 16 14 8 18 1 6 5 3 13 7 17 11 9 15 19
//Blocking:28270 msec; non-blocking: 1107 msec
static void Main(string[] args)
{
var uri = "http://www.corebvba.be/blog";
var n = 20;
var blockingsw = new Stopwatch();
blockingsw.Start();
Parallel.For(0,n,i=> {
var s = DownloadString(uri);
Console.Write(i.ToString() + " ");
});
blockingsw.Stop();
Console.WriteLine();
var nonblockingsw = new Stopwatch();
nonblockingsw.Start();
Parallel.For(0,n,i=> {
var s = DownloadString(uri);
Console.Write(i.ToString()+" ");
});
nonblockingsw.Stop();
Console.WriteLine();
Console.WriteLine("Blocking:{0} msec; non-blocking: {1} msec", blockingsw.ElapsedMilliseconds, nonblockingsw.ElapsedMilliseconds);
Console.ReadLine();
}
static string DownloadString(string uri)
{
return new WebClient().DownloadString(uri);
}
static string DownloadStringNonBlocking(string uri)
{
string result = null;
var wc = new WebClient();
Wait.Async(done =>
{
wc.DownloadStringCompleted+=(s,e)=> { result = e.Result; done();};
wc.DownloadStringAsync(new Uri(uri));
});
return result;
}
static class Wait
{
public static void Async(Action<Action> What)
{
var re = new ManualResetEvent(false);
What(()=>re.Set());
re.WaitOne();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Paycento.API.Tasks
{
public static class Wait
{
public static void Async(Action<Action> what)
{
var re = new ManualResetEvent(false);
what(() => re.Set());
re.WaitOne();
}
public static IEnumerable<T> AsAsync<T>(this IQueryable<T> what, System.Data.Linq.DataContext db)
{
var cmd = db.GetCommand(what) as System.Data.SqlClient.SqlCommand;
if (cmd == null) return what;
var conn = new System.Data.SqlClient.SqlConnection(db.Connection.ConnectionString + ";Asynchronous Processing=True;");
conn.Open();
cmd.Connection = conn;
IAsyncResult res = null;
Wait.Async(done =>
{
res = cmd.BeginExecuteReader(x => done(), null,System.Data.CommandBehavior.CloseConnection);
});
var rdr = cmd.EndExecuteReader(res);
return db.Translate<T>(rdr);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment