private static void SendMultiThreadRequest(List<int> acitivityIds, int threadCounts, SendRequestDelegate sendRequestDelegate) { var startTime = DateTime.Now; var eventWaitHandles = new AutoResetEvent[threadCounts]; int perThreadItems = acitivityIds.Count / threadCounts == 0 ? acitivityIds.Count / threadCounts : acitivityIds.Count / threadCounts + 1; for (int i = 0; i < threadCounts; i++) { var items = acitivityIds.GetRange(perThreadItems * i, i == threadCounts - 1 ? acitivityIds.Count - perThreadItems * i : perThreadItems); eventWaitHandles[i] = new AutoResetEvent(false); Console.WriteLine("thread count:{0}, i:{1}", threadCounts, i); //why need to define another variable i1? int i1 = i; var thread = new Thread(() => SendRequestBySingleThread(items, sendRequestDelegate, eventWaitHandles[i1])) {Name = i.ToString()}; thread.Start(); } WaitHandle.WaitAll(eventWaitHandles); var endTime = DateTime.Now; Console.WriteLine("done!"); Console.WriteLine("total time spent:{0}", endTime - startTime); }
private static void SendRequestBySingleThread(List<int> activityIds, SendRequestDelegate sendRequest, AutoResetEvent eventWaitHandle) { var startTime = DateTime.Now; foreach (var activityId in activityIds) { Console.WriteLine(string.Format("Thread:{0}, Id:{1}", Thread.CurrentThread.Name, activityId.ToString())); sendRequest(activityId); //Thread.Sleep(1000); } eventWaitHandle.Set(); var endTime = DateTime.Now; Console.WriteLine("thread {0} request count:{1}, time spent:{2}", Thread.CurrentThread.Name, activityIds.Count, endTime - startTime); }
public SendRequestState(SendRequestDelegate d, Action<XDocument> callback) { Delegate = d; Callback = callback; }
public static IAsyncResult GetResponseAsync(Dictionary<string, string> parameters, Action<XDocument> callback) { var httpMethod = "GET"; var authNeeded = false; var isSsl = false; RequestParametersAttribute attr = null; var a = new StackFrame(1, false).GetMethod().GetCustomAttributes(typeof(RequestParametersAttribute), false); if (a.Length > 0) attr = a[0] as RequestParametersAttribute; if (attr != null) { httpMethod = attr.HttpMethod.ToString(); authNeeded = attr.AuthNeeded; isSsl = attr.IsSsl; } Logger.WriteEmptyLine(); Logger.LogMessage(parameters["method"], "Request"); var d = new SendRequestDelegate(SendRequest); return d.BeginInvoke( parameters, httpMethod, authNeeded, isSsl, new AsyncCallback((res) => { var s = (SendRequestState)res.AsyncState; var doc = s.Delegate.EndInvoke(res); if (doc != null) // no exceptions occured { Logger.LogMessage("Last.fm response OK"); //Logger.LogMessage(Environment.NewLine + doc.Document.ToString(), "Last.fm response"); if (s.Callback != null) s.Callback(doc); } }), new SendRequestState(d, callback)); }