static void Main() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); // Poll while simulating work. while (result.IsCompleted == false) { Thread.Sleep(250); Console.Write("."); } // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
private void button3_Click(object sender, EventArgs e) { var caller = new AsyncMethodCaller(AsyncMethod); MessageBox.Show("Task Created."); IAsyncResult result = caller.BeginInvoke(2000, CallbackMethod, null); MessageBox.Show("Task BeginInvoke."); }
static void Main(string[] args) { // The asynchronous method puts the thread id here. int threadId; // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); //Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
static void Start() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. var ad = new AsyncDemo(); // Create the delegate. var caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. var result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. var returnValue = caller.EndInvoke(out threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Console.ReadKey(); }
static void Main() { int threadId; AsyncDemo ad = new AsyncDemo(); AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); result.AsyncWaitHandle.WaitOne(); string returnValue = caller.EndInvoke(out threadId, result); result.AsyncWaitHandle.Close(); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Console.ReadKey(true); }
protected void Page_Load(object sender, EventArgs e) { Debug.WriteLine("Starting"); DateTime? a = new DateTime(2000, 12, 5); a = null; TheDelegate delegateDefinition = s => s; string theReturnValue = delegateDefinition("test"); AsyncDemo ad = new AsyncDemo(); AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); int dummy = 0; IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Debug.WriteLine(string.Format("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId)); //Thread.Sleep(4000); Debug.WriteLine("The main thread ends."); }
//EndInvokeによるブロッキング static void BlockingEndInvoke() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // Initiate the asychronous call. // デリゲートを同じ引き数+コールバック関数+コールバック引数となります。 IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Call EndInvoke to wait for the asynchronous call to complete, // and to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
public void Send(MailMessage message) { MailMessage msg = new MailMessage(); msg = message; AsyncMethodCaller caller = new AsyncMethodCaller(SendMailInSeperateThread); AsyncCallback callbackHandler = new AsyncCallback(AsyncCallback); caller.BeginInvoke(msg, callbackHandler, null); }
private void button2_Click(object sender, EventArgs e) { var caller = new AsyncMethodCaller(AsyncMethod); MessageBox.Show("Task Created."); IAsyncResult result = caller.BeginInvoke(2000, null ,null); MessageBox.Show("Task BeginInvoke."); Thread.Sleep(100); caller.EndInvoke(result); MessageBox.Show("Task EndInvoke."); }
public static void Main(string[] args) { // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // The threadId parameter of TestMethod is an out parameter, so // its input value is never used by TestMethod. Therefore, a dummy // variable can be passed to the BeginInvoke call. If the threadId // parameter were a ref parameter, it would have to be a class- // level field so that it could be passed to both BeginInvoke and // EndInvoke. int dummy = 0; // Initiate the asynchronous call, passing three seconds (3000 ms) // for the callDuration parameter of TestMethod; a dummy variable // for the out parameter (threadId); the callback delegate; and // state information that can be retrieved by the callback method. // In this case, the state information is a string that can be used // to format a console message. IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); // The callback is made on a ThreadPool thread. ThreadPool threads // are background threads, which do not keep the application running // if the main thread ends. Comment out the next line to demonstrate // this. Thread.Sleep(4000); Console.WriteLine("The main thread ends."); Console.ReadKey(); }
public ActionResult Index() { var client = new FlickrService.FlickrService(); AsyncMethodCaller caller = new AsyncMethodCaller(client.GetRecentPhotos); var result = caller.BeginInvoke(null, null); var photos = caller.EndInvoke(result); ViewData["flickrphotos"] = photos; List<string> urls = new List<string>(); foreach (var photo in photos) { urls.Add(photo.ImageUrl); } ViewData["photos"] = urls; return View(); }
static void Main() { AsyncDemo ad = new AsyncDemo(); AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); int dummy = 0; IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(4000); Console.WriteLine("The main thread ends."); Console.ReadKey(true); }
static int Main(string[] args) { IAsyncResult result = null; AsyncMethodCaller caller = new AsyncMethodCaller(DelegateCommon.TestMethod); try { result = caller.BeginInvoke(123, null, null); } catch (PlatformNotSupportedException) { // Expected } catch (Exception ex) { Console.WriteLine("BeginInvoke resulted in unexpected exception: {0}", ex.ToString()); Console.WriteLine("FAILED!"); return -1; } try { caller.EndInvoke(result); } catch (PlatformNotSupportedException) { // Expected } catch (Exception ex) { Console.WriteLine("EndInvoke resulted in unexpected exception: {0}", ex.ToString()); Console.WriteLine("FAILED!"); return -1; } return 100; }
static void Main() { int threadId; AsyncDemo ad = new AsyncDemo(); AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); while (result.IsCompleted == false) { Thread.Sleep(250); Console.Write("."); } string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Console.ReadKey(true); }
void AsyncJobByDelegate() { AsyncMethodCaller caller = new AsyncMethodCaller(SleepJob); caller.BeginInvoke(GetResult, null); }
private static void BeginInvokeOnDelegateWithLambdaCallback1() { var caller = new AsyncMethodCaller(AsyncMethod); caller.BeginInvoke("delegate", result => { }, null); // Noncompliant }
private static void BeginInvokeAndEndInvokeOnDelegateWithLambdaCallback1() { var caller = new AsyncMethodCaller(AsyncMethod); caller.BeginInvoke(name: "delegate", @object: null, callback: result => caller.EndInvoke(result)); // Compliant }
public static Foo operator +(Foo b, Foo c) { caller.BeginInvoke("prop", null, null); // Noncompliant return(new Foo()); }
//非同期呼び出し完了じのコールバックによる待機 static void BlockingCollBack() { // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // The threadId parameter of TestMethod is an out parameter, so // its input value is never used by TestMethod. Therefore, a dummy // variable can be passed to the BeginInvoke call. If the threadId // parameter were a ref parameter, it would have to be a class- // level field so that it could be passed to both BeginInvoke and // EndInvoke. int dummy = 0; // Initiate the asynchronous call, passing three seconds (3000 ms) // for the callDuration parameter of TestMethod; a dummy variable // for the out parameter (threadId); the callback delegate; and // state information that can be retrieved by the callback method. // In this case, the state information is a string that can be used // to format a console message. IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); // mainスレッドを待機させる3秒以上待機させても問題ない。 //Thread.Sleep(4000); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); Console.WriteLine("The main thread ends."); }
static void Main() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); IAsyncResult result; #region Using Begin and End Invoke Console.WriteLine("Beginning solely end invoke method..."); // Initiate the asynchronous call. result = caller.BeginInvoke(1111, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Call EndInvoke to wait for the asynchronous call to complete, // and to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, has completed using EndInvoke (blocking) with return value \"{1}\".", threadId, returnValue); Console.WriteLine(); #endregion ad = new AsyncDemo(); caller = new AsyncMethodCaller(ad.TestMethod); #region Using a Wait Handle Console.WriteLine("Beginning wait handle method..."); result = caller.BeginInvoke(1234, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some more work.", Thread.CurrentThread.ManagedThreadId); // Wait for the WaitHandle to become signalled. result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. returnValue = caller.EndInvoke(out threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine("The called executed on thread {0}, has completed using a Wait Handle with return value \"{1}\".", threadId, returnValue); Console.WriteLine(); #endregion ad = new AsyncDemo(); caller = new AsyncMethodCaller(ad.TestMethod); #region Using Polling Console.WriteLine("Beginning polling method..."); result = caller.BeginInvoke(1010, out threadId, null, null); // Poll while simulating work. while (result.IsCompleted == false) { Thread.Sleep(250); Console.Write("."); } returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("\nThe call executed on thread {0}, has completed using polling with return value \"{1}\".", threadId, returnValue); Console.WriteLine(); #endregion ad = new AsyncDemo(); caller = new AsyncMethodCaller(ad.TestMethod); #region Using an AsyncCallBack method Console.WriteLine("Beginning asynchronous callback method..."); /* AsyncCallback callback = new AsyncCallback(ad.AsyncCallBackMethod); result = caller.BeginInvoke(1234, out threadId, callback, null); callback(result); */ result = caller.BeginInvoke(1234, out threadId, new AsyncCallback(ad.AsyncCallBackMethod), "The call executed on thread {0}, with return value \"{1}\"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); // The callback is made on a threadpool thread. Threadpool threads // are background threads, which do not keep the application running // if the main thread ends. Comment out the next line to demonstrate // this. Thread.Sleep(4000); Console.WriteLine("The main thread ends."); Console.WriteLine(); #endregion #region My own test Console.WriteLine("Running my own test..."); AsyncThingy thingy = new AsyncThingy(); thingy.DoAsyncStuff(); Console.WriteLine("Main thread {0} is back.", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("The asynchronous method should write something shortly, or stuff will explode"); Thread.Sleep(6000); #endregion }
private void btnBatchUpdateLocalAssembly_Click(object sender, EventArgs e) { tabMain.SelectedTab = tabPageMessage; if (Configuration.MasterConfig.BatchUpdateAssemblySettings.AutoUpdate) { AsyncMethodCaller caller = new AsyncMethodCaller(InitializeDropdowns); IAsyncResult result = caller.BeginInvoke( null, caller); caller.EndInvoke(result); for (int i = 0; i < cmbVersion.Items.Count; i++) { cmbVersion.SelectedIndex = i; for (int j = 1; j < cmbModule.Items.Count; j++) { cmbModule.SelectedIndex = j; foreach (String uri in Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateModuleNames) { if (uri.ToLower() == cmbModule.Text.ToLower()) { string updateUrl = textEndPointUri.Text.ToLower(); if (!updateUrls.Contains(updateUrl)) { updateUrls.Add(updateUrl); } } } } } } string[] updateVersions = Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateVersions; string[] updateModuleNames = Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateModuleNames; if (updateVersions != null && updateModuleNames != null) { for (int i = 0; i < updateVersions.Length; i++) { for (int j = 0; j < updateModuleNames.Length; j++) { string updateUrl = updateVersions[i] + updateModuleNames[j]; if (!updateUrls.Contains(updateUrl)) { updateUrls.Add(updateUrl); } } } } beginUpdateLocalAssembly = 0; finishedUpdateLocalAssembly = 0; btnBatchUpdateLocalAssembly.Enabled = false; foreach (string updateUrl in updateUrls) { beginUpdateLocalAssembly++; Wsdl wsdl1 = new Wsdl(); wsdl1.Paths.Add(updateUrl); AsyncMethodCaller caller1 = new AsyncMethodCaller(wsdl1.GenerateAndUpdateAssembly); caller1.BeginInvoke( new AsyncCallback(BatchUpdateLocalAssemblyCallBack), caller1); ShowMessage(this, MessageType.Begin, "Begin Create Local Assembly Use EndPointUri: " + updateUrl); } }
private static void BeginInvokeOnDelegateWithoutCallback() { var caller = new AsyncMethodCaller(AsyncMethod); caller.BeginInvoke("delegate", /* callback */ null, /* state */ null); // Noncompliant }
private static void BeginInvokeAndEndInvokeOnDelegateWithDelegateCallback() { var caller = new AsyncMethodCaller(AsyncMethod); caller.BeginInvoke("delegate", delegate(IAsyncResult result) { caller.EndInvoke(result); }, null); // Compliant }
static void Main() { // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // The threadId parameter of TestMethod is an out parameter, so // its input value is never used by TestMethod. Therefore, a dummy // variable can be passed to the BeginInvoke call. If the threadId // parameter were a ref parameter, it would have to be a class- // level field so that it could be passed to both BeginInvoke and // EndInvoke. int dummy = 0; // Initiate the asynchronous call, passing three seconds (3000 ms) // for the callDuration parameter of TestMethod; a dummy variable // for the out parameter (threadId); the callback delegate; and // state information that can be retrieved by the callback method. // In this case, the state information is a string that can be used // to format a console message. //IAsyncResult result = caller.BeginInvoke(3000, // out dummy, // new AsyncCallback(CallbackMethod), // "The call executed on thread {0}, with return value \"{1}\"."); //IAsyncResult result = caller.BeginInvoke(3000, out dummy, delegate(IAsyncResult ar) //{ // //// Retrieve the delegate. // //AsyncResult result = (AsyncResult)ar; // //AsyncMethodCaller calle = (AsyncMethodCaller)result.AsyncDelegate; // // Retrieve the format string that was passed as state // // information. // string formatString = (string)ar.AsyncState; // // Define a variable to receive the value of the out parameter. // // If the parameter were ref rather than out then it would have to // // be a class-level field so it could also be passed to BeginInvoke. // int threadId = 0; // // Call EndInvoke to retrieve the results. // string returnValue = caller.EndInvoke(out threadId, ar); // // Use the format string to format the output message. // Console.WriteLine(formatString, threadId, returnValue); //}, "The call executed on thread {0}, with return value \"{1}\"."); IAsyncResult result = caller.BeginInvoke(3000, out dummy, (ar) => { //// Retrieve the delegate. //AsyncResult result = (AsyncResult)ar; //AsyncMethodCaller calle = (AsyncMethodCaller)result.AsyncDelegate; // Retrieve the format string that was passed as state // information. string formatString = (string)ar.AsyncState; // Define a variable to receive the value of the out parameter. // If the parameter were ref rather than out then it would have to // be a class-level field so it could also be passed to BeginInvoke. int threadId = 0; // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, ar); // Use the format string to format the output message. Console.WriteLine(formatString, threadId, returnValue); }, "The call executed on thread {0}, with return value \"{1}\"."); // 执行50毫秒后超时 result.AsyncWaitHandle.WaitOne(50, true); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); // The callback is made on a ThreadPool thread. ThreadPool threads // are background threads, which do not keep the application running // if the main thread ends. Comment out the next line to demonstrate // this. Thread.Sleep(4000); Console.WriteLine("The main thread ends."); }
//WaitHandle による非同期呼び出しの待機 static void BlockingWaitHandle() { // スレッドID保存用の変数を宣言 int threadId; //AsyncDemoクラスをインスタンス化 AsyncDemo ad = new AsyncDemo(); //AsyncDemoのデリゲート型を使用してデリゲートを作成 AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); // デリゲートのBeginInvokeを使用してThreadPoolで処理を開始 // 引数#1はデリゲートの引数1引数#2はデリゲートの第二引数 // #3,コールバック関数を利用する場合、#4はコールバック関数の引数 IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); }
public IAsyncResult BeginInvoke(AsyncMethodCaller method) { return(method.BeginInvoke("NotADelegate", result => { method.EndInvoke(result); }, null)); }
private void DoTestAsyncOperation() { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(1000, out threadId, null, null); result.AsyncWaitHandle.WaitOne(); Trace.Write("BeginAsyncOperation", string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}", threadId, result.AsyncState, caller)); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>; if (threadIds != null) threadIds.Enqueue(threadId); if (m_AsyncResults != null) m_AsyncResults.Add(threadId, result); // Close the wait handle. result.AsyncWaitHandle.Close(); }
private void button1_Click(object sender, EventArgs e) { if (txtParameters.Count > 0) { if (MessageBox.Show("请确认参数是否全部填写正确!", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return; } button1.Enabled = false; label5.Text = "正在调用服务,请稍候..."; label5.Refresh(); var jValue = new JObject(); if (txtParameters.Count > 0) { foreach (var p in txtParameters) { var text = p.Value.Text.Trim(); if (!string.IsNullOrEmpty(text)) { var info = p.Value.Tag as ParameterInfo; try { jValue[p.Key] = JToken.Parse(text); } catch { jValue[p.Key] = text; } } } } //提交的参数信息 string parameter = jValue.ToString(Newtonsoft.Json.Formatting.None); var message = new InvokeMessage { ServiceName = serviceName, MethodName = methodName, Parameters = parameter }; //启用线程进行数据填充 var caller = new AsyncMethodCaller(AsyncCaller); var ar = caller.BeginInvoke(message, AsyncComplete, caller); }
private void AsyncInitializeDropdowns() { btnPopulate.Enabled = false; cmbModule.Enabled = false; cmbVersion.Enabled = false; ServerCBox.Enabled = false; buttonGet.Enabled = false; AsyncMethodCaller caller = new AsyncMethodCaller(InitializeDropdowns); caller.BeginInvoke( new AsyncCallback(InitializeDropdownsCallBack), caller); }
public void FoundWayAsync(Point startPosition, Point endPosition) { HasEnded = false; AsyncMethodCaller caller = new AsyncMethodCaller(FoundPath); caller.BeginInvoke(startPosition, endPosition, null, null); // Thread thread = new Thread(caller(startPosition, endPosition, out path, creature, improvedPathFinding, ignoreObstacles)}); }
private void RegenerateCache(string url) { var method = new AsyncMethodCaller(GenerateIndexesFor); method.BeginInvoke(url, null, null); }
private static void BeginInvokeOnDelegateWithDelegateCallback() { var caller = new AsyncMethodCaller(AsyncMethod); caller.BeginInvoke("delegate", delegate(IAsyncResult result) { Console.WriteLine(); }, null); // Noncompliant }
public void BuyNumber(Int32 number, Action<NumberType> callback) { // no lock is needed here since just checking if a number is prime // and its a readonly operation. if (!_primes.ContainsKey(number)) { callback(NumberType.NotExist); } else { // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(BuyPrime); // Initiate the asychronous call. caller.BeginInvoke(number, callback, null, null); } }
/// <summary> /// Executes a particular function in a module, according to the passed in parameters, acting as a slave server /// </summary> /// <param id="state">The server state object of the request</param> public static void ExecutionBegin(ServerState state) { //finally execute the function defined in the transfer AsyncMethodCaller execution = new AsyncMethodCaller(execute); execution.BeginInvoke(state, null, null); }
/// <summary> /// Main: Async operation beginning using WaitOne (waithandler) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="cb"></param> /// <param name="state"></param> /// <returns></returns> IAsyncResult BeginAsyncOperation(object sender,EventArgs e,AsyncCallback cb,object state) { // The asynchronous method puts the thread id here. int threadId; // Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); Thread.Sleep(0); Console.WriteLine("Main thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, //null, null); new AsyncCallback(EndAsyncOperation), "The call executed on thread {0}, with return value \"{1}\"."); Trace.Write("BeginAsyncOperation", string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}) ", threadId, result.AsyncState, caller)); result.AsyncWaitHandle.WaitOne(); // Perform additional processing here. // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue); Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>; if (threadIds != null) threadIds.Enqueue(threadId); IDictionary<int, IAsyncResult> asyncResult = m_AsyncResults;// Session["AsyncResults"] as Dictionary<int, IAsyncResult>; if (asyncResult != null) asyncResult.Add(new KeyValuePair<int, IAsyncResult>(threadId, result)); IDictionary<int, AsyncMethodCaller> asyncCallers = m_AsyncCallers;// Session["AsyncCallers"] as Dictionary<int, AsyncMethodCaller>; if (asyncCallers != null) asyncCallers.Add(new KeyValuePair<int, AsyncMethodCaller>(threadId, caller)); // Close the wait handle. result.AsyncWaitHandle.Close(); return result; }
public void FoundWayAsync(Point startPosition, Point endPosition) { HasEnded = false; AsyncMethodCaller caller = new AsyncMethodCaller(FindPath); caller.BeginInvoke(startPosition, endPosition, null, null); }
/// <summary> /// Load a category of videos into this carousel. /// Everything calling the webservice and downloading of coverart is run in a background thread. /// </summary> /// <param name="category"></param> public void Add(string category) { AsyncMethodCaller caller = new AsyncMethodCaller(InternalAdd); IAsyncResult result = caller.BeginInvoke(category, null, null); }
private void UpdateItems() { if (!player.IsLogined()) { Debug.LogError("player do not login!"); ShowDialog("获取角色", "与服务器断开或用户未登陆!", true, () => { player.Logout(); SceneManager.LoadScene("start"); }, () => { player.Logout(); SceneManager.LoadScene("start"); }); } ShowDialog("获取角色", "处理中...", false); string data = Processor.C2SGetRoles(player.userId); player.Send(data); AsyncMethodCaller caller = new AsyncMethodCaller(AcquireRoles); IAsyncResult result = caller.BeginInvoke(null, null); bool success = result.AsyncWaitHandle.WaitOne(10000, true); if (!success) { Debug.Log("Time Out"); ShowDialog("获取角色", "获取已创建角色失败!", true, () => { player.Logout(); SceneManager.LoadScene("start"); }, () => { player.Logout(); SceneManager.LoadScene("start"); }); } else { List <Role> roles = player.roles; for (int i = 0; i < 3; ++i) { Image item = items[i]; if (i < roles.Count) { Text[] texts = item.GetComponentsInChildren <Text> (); string name = roles [i].name; string description = string.Format("level:{0,4} HP:{1}\nEXP:{2,3} weapon:{3}\nattack:{4,3} ammunition:{5}", roles [i].level, roles [i].maxHP, roles [i].exp, roles [i].weapon, roles [i].attack, roles [i].ammunition == -1 ? "无限" : roles [i].ammunition.ToString()); foreach (Text t in texts) { switch (t.name) { case "name": t.text = name; break; case "description": t.text = description; break; } } item.gameObject.SetActive(true); } else { item.gameObject.SetActive(false); } } } result.AsyncWaitHandle.Close(); HideDialog(); }