zoukankan      html  css  js  c++  java
  • Thread Basics(thread synchronization&Asynchronization) part two

    i.respective classes and interfaces related asychronouse invoking in .Net FrameWork.
          a) IAsycResult  interface
                IAsyncResult stores relative asynchronouse invoking information,including the following
            --------------------------------------------------------------------
                property                    type                        comments
            --------------------------------------------------------------------
           AsyncState                     Object                                  additional data invoking method
           AsyncWaitHandle           System.Treading.WaitHandle     to wait synchronouse object until OP finished.
          CompletedSynchronously    bool                                   
           IsCompleted                      bool                                   operation has finished or not?
            
            Invoking BeginInvoke() of delegate wll return an ISyncResult reference, and the same applies to BeginXXX(). 

    ii. Simple sample about Threads executing synchronousely and asynchronousely

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;

    namespace MyThread
    {
        public class ThreadUnits
        {
            public static string ThreadDescription(Thread thread)
            {
                StringBuilder sb = new StringBuilder(100);
                if (thread.Name != null && thread.Name != "")
                {
                    sb.Append(thread.Name);
                    sb.Append(", ");
                }

                sb.Append("hash: ");
                sb.Append(thread.GetHashCode());
                sb.Append(", pool:");
                sb.Append(thread.IsThreadPoolThread);
                sb.Append(", backgrnd");
                sb.Append(thread.IsBackground);
                sb.Append(", state");
                sb.Append(thread.ThreadState);
                return sb.ToString();


            }

            public static void DisplayThreadInfo(string context)
            {
                string output = "\n" + context + "\n" + ThreadDescription(Thread.CurrentThread);
                Console.WriteLine(output);
            }
        }

         public class DataRetriever
        {
            public string GetAddress(string name)
            {
                ThreadUnits.DisplayThreadInfo("In GetAddress...");
                //simulate waiting to get results off database servers.
              
                    Thread.Sleep(1000);
                    if (name == "Simon")
                        return "Simon lives in Lancaster";
                    else if (name == "Wrox Press")
                        return "Wrox Press lives in Acocks Green";
                    else
                        return name + "is not in database                     
            }

            public delegate string GetAddressDelegate(string name);       
            public void GetAddressSync(string name)
            {
                try
                {
                    GetAddressDelegate dc = new GetAddressDelegate(this.GetAddress);
                    string result = dc(name);
                    Console.WriteLine("\n Sync:" + result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nSync: a problem occurred:" + ex.Message);
                }
            }

            //BeginInvoke和EndInvoke显式调用,不用回调函数
             public void GetAddressAsyncWait(string name)
            {
                GetAddressDelegate dc = new GetAddressDelegate(this.GetAddress);

                IAsyncResult ar = dc.BeginInvoke(name, null, null);
                   //此处没有利用回调函数 AsyncCallBack,因此用EndInvoker显式关闭
                    /*
                        Main Thread can do other work now。。。。
                    */
        
            try
                {
                    string result = dc.EndInvoke(ar);
                    Console.WriteLine("\nAsync waiting:" + result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nAsync Waiting, a problem occurred:" + ex.Message);
                }

            }

            public void GetResultsOnCallback(IAsyncResult ar)
            {
                GetAddressDelegate del = (GetAddressDelegate)((AsyncResult)ar).AsyncDelegate;
                    //AsyncResult comf from : System.Runtime.remoting.message;
                    //especial notes: IAsyncResult   ->System.Threading;
                  //                         AsyncResult   ->System.Runtime.Remoting.message;

                try
                {
                    string result;
                    result = del.EndInvoke(ar);
                    Console.WriteLine("\nOn CallBack :result is " + result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("On Callback, problem occurred: "+ex.Message);
                }
            }

            //BeginInvoke之后,利用回调函数返回结果
            public void GetAddressAsync(string name)
            {
                GetAddressDelegate dc = new GetAddressDelegate(this.GetAddress);
                AsyncCallback cb = new AsyncCallback(this.GetResultsOnCallback);
                IAsyncResult ar = dc.BeginInvoke(name, cb, null);
            }

        }

        public class EntryPoint
        {
            public static void Main()
            {
                Thread.CurrentThread.Name = "Main Thread";
                DataRetriever dr = new DataRetriever();

                //Synchronization
                dr.GetAddressSync("Simon");
                dr.GetAddressSync("Wrox Press");
                dr.GetAddressSync("Herengang");
               
                 //Asynchronization without callback      
                dr.GetAddressAsync("Simon");
                dr.GetAddressAsync("Herengang");
                dr.GetAddressAsync("Wrox Press");

                //Asynchronization with callback                   
                dr.GetAddressAsyncWait("Simon");
                dr.GetAddressAsyncWait("Wrox Press");
                dr.GetAddressAsyncWait("Herengang");
                
                
                Console.WriteLine("thread finished");           
                Console.Read();
            }
        }
    }
    if everything goes well, you will see the following window:

  • 相关阅读:
    IT项目中使用 json格式数据 保存项目配置信息, 在配置文件再读取json文件的内容进行赋值
    python 使用eval() 可以将json格式的数据,转换为原始数据
    python 取出字典的键或者值/如何删除一个字典的键值对/如何遍历字典
    python2 中 unicode 和 str 之间的转换及与python3 str 的区别
    python 将列表嵌套字典的unicode字符串转换为str格式的字符串的方法
    Django 项目拆分配置文件settings.py
    苹果笔记本调整 pycharm 字体大小的地方
    django rest framework 向数据库中插入数据时处理外键的方法
    java实现文件的压缩和解压
    java 跨数据库导入大数据
  • 原文地址:https://www.cnblogs.com/Winston/p/1132476.html
Copyright © 2011-2022 走看看