YongGang Meng's Weblog


Welcome to Weblog
Use UdpClient to send and receive message
Client to receive message sent by server:
 
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Linq;
   7:  using System.Text;
   8:  using System.Windows.Forms;
   9:  using System.Net.Sockets;
  10:  using System.Threading;
  11:  using System.Net;
  12:   
  13:  namespace NoticeSystemClient
  14:  {
  15:      public partial class MainForm : Form
  16:      {
  17:          public delegate void ShowMessage(string message);
  18:          public ShowMessage myDelegate;
  19:          Int32 port = 11000;
  20:          UdpClient udpClient = new UdpClient(11000);
  21:          Thread thread;
  22:          public MainForm()
  23:          {
  24:              //CheckForIllegalCrossThreadCalls = false;
  25:              InitializeComponent();
  26:          }
  27:   
  28:          private void MainForm_KeyDown(object sender, KeyEventArgs e)
  29:          {
  30:              if (e.KeyCode == Keys.Escape)
  31:              {
  32:                  thread.Abort();
  33:                  udpClient.Close();
  34:                  Close();
  35:              }
  36:          }
  37:   
  38:          private void ReceiveMessage()
  39:          {                      
  40:              while (true)
  41:              {
  42:                  IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
  43:                  byte[] content = udpClient.Receive(ref remoteIPEndPoint);
  44:   
  45:                  if (content.Length > 0)
  46:                  {
  47:                      string message = Encoding.ASCII.GetString(content);
  48:                      
  49:                      this.Invoke(myDelegate, new object[] { message });
  50:                  }
  51:              }
  52:          }
  53:   
  54:   
  55:          private void ShowMessageMethod(string message)
  56:          {
  57:              richText.Text = message;
  58:          }
  59:   
  60:          private void MainForm_Load(object sender, EventArgs e)
  61:          {            
  62:              myDelegate = new ShowMessage(ShowMessageMethod);
  63:              thread = new Thread(new ThreadStart(ReceiveMessage));
  64:              thread.IsBackground = true;
  65:              thread.Start();
  66:          }
  67:      }
  68:  }

Server:

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Linq;
   7:  using System.Text;
   8:  using System.Windows.Forms;
   9:  using System.Net.Sockets;
  10:  using System.Net;
  11:   
  12:  namespace NoticeSystem
  13:  {
  14:      public partial class MainForm : Form
  15:      {
  16:          UdpClient udpClient = new UdpClient();
  17:          public MainForm()
  18:          {
  19:              InitializeComponent();
  20:          }
  21:   
  22:          private void btnClose_Click(object sender, EventArgs e)
  23:          {
  24:              udpClient.Close();
  25:              Close();
  26:          }
  27:   
  28:          private void btnSend_Click(object sender, EventArgs e)
  29:          {
  30:              Int32 port = 11000;
  31:              IPAddress ip = IPAddress.Parse(txtStartIP.Text.Trim());
  32:              IPEndPoint ipEndPoint = new IPEndPoint(ip,port);
  33:              byte[] content = Encoding.ASCII.GetBytes(richText.Text);
  34:              try
  35:              {
  36:                  int count = udpClient.Send(content, content.Length, ipEndPoint);
  37:                  if (count > 0)
  38:                  {
  39:                      MessageBox.Show("Message has been sent.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
  40:                  }
  41:              }
  42:              catch
  43:              {
  44:                  MessageBox.Show("Error occurs.", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  45:              }
  46:          }
  47:      }
  48:  }

There’s no more to say but the Client source code, red words.

We must indicate the port of the UdpClient, otherwise, it will pop errors.

code:

UdpClient udpClient = new UdpClient(11000);

At the outset, i don’t indicate the port, so when i debug the code, there’s nothing happen on client side.

Source code disassembled by Red Gate’s .Net Reflector of the UdpClient:

   1:  public UdpClient(int port) : this(port, AddressFamily.InterNetwork)
   2:  {
   3:  }

 

   1:  public UdpClient(int port, AddressFamily family)
   2:  {
   3:      IPEndPoint point;
   4:      this.m_Buffer = new byte[0x10000];
   5:      this.m_Family = AddressFamily.InterNetwork;
   6:      if (!ValidationHelper.ValidateTcpPort(port))
   7:      {
   8:          throw new ArgumentOutOfRangeException("port");
   9:      }
  10:      if ((family != AddressFamily.InterNetwork) && (family != AddressFamily.InterNetworkV6))
  11:      {
  12:          throw new ArgumentException(SR.GetString("net_protocol_invalid_family"), "family");
  13:      }
  14:      this.m_Family = family;
  15:      if (this.m_Family == AddressFamily.InterNetwork)
  16:      {
  17:          point = new IPEndPoint(IPAddress.Any, port);
  18:      }
  19:      else
  20:      {
  21:          point = new IPEndPoint(IPAddress.IPv6Any, port);
  22:      }
  23:      this.createClientSocket();
  24:      this.Client.Bind(point);
  25:  }
 
You will find that the UdpClient need a port to bind to to listen the IPENDPOINT.
Posted: May 22 2009, 08:05 AM by Ralax | with 3 comment(s)
Filed under: , , ,
Excel data type seems strange when use ado.net to select

Recently, we need import some data from excel to  Oracle database. A strange thing confused me.

The excel file has a column, for example PhoneNumber, the format is 999999,

here are some example data:

  • 123456
  • 234561
  • 345612
  • 456123
  • 561234
  • 612345
  • 000123
  • 000231
  • 000312

When i use the following code to select data, something is strange.

   1:  string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + ftpFile.PostedFile.FileName + ";" 
   2:                   + "Extended Properties=\"Excel 8.0;IMEX=1\"";
   3:  DataSet ds = new DataSet();
   4:  string strSql = "select * from [Sheet1$]";
   5:  using (OleDbDataAdapter adp = new OleDbDataAdapter(strSql, strConn))
   6:  {
   7:        adp.Fill(ds, "Phone");
   8:  }

view the ds data, you will find this:

  • 123456
  • 234561
  • 345612
  • 456123
  • 561234
  • 612345
  •             

if i change the number format to text, i still can not retrieve the number start with 000.

 

I don’t know why, finally i change every number to string in excel file. for example: 123456---> ‘123456 and 000123--->’000123. it works.

anyone who has a good solution for this?

Posted: May 22 2009, 06:59 AM by Ralax | with 1 comment(s)
Filed under: , , ,
Problem about SQLite and Linq to Entities

I have a web project developed in VS2008, which use System.Data.SQLite for .Net 2.0 and Linq to Entities to access data.

Here is the source layout:

image

image

image

You can see that i have a SQLite database Test_DB.db3 in SQLite folder. In my develop machine, i use connectiongstring created by Linq to Entities named “Test_DBEntities”, and don’t have the DBProviderFactories section, it run well. The Default.aspx page display data and the pages in Admin folder manage the data.

I publish the website in my product machine, it can not run, the error is “Could not load the assembly System.Data.SQLite”,

I search a solution, which ask me add the DBProviderFactories to the web.config file and add new reference to System.Data.SQLite.Linq.ddl. After do this, i can view the Default.aspx which display data. But i can not manage my data through the pages in Admin folder. I get error “Can not open the database file”, some people said the database can not in App_Data, but my file is not in App_Data, i still get the error.

I feel strange when i view the default.aspx, Test.edmx get data successfully, but when i view pages in Admin, for example, Manage.aspx, it will get the error “Can not open the database file”, The Manage.aspx get data only, no else. Following is my code to access data:

using (Test_DBEntities osDataContext = new Test_DBEntities(Common.GetConnString()))
{                    
     OS_Module module = osDataContext.OS_Module.First<OS_Module>(m => m.Status == "Y" && m.ModuleValue == this.ModuleValue);
       this.modelTitle.InnerHtml = module.ModuleTitle;
       this.modelDetail.InnerHtml = Server.HtmlDecode(module.ModuleDetail);
}

I can use Default.aspx display different data, which get data successfully each time, but when display data use Manage.aspx in Admin folder, i will get the error “Can not open the database file”.

Any one who gets a solution, please comment here. Thanks very much!

Export data to excel or word

In the actual develpment, we offen encounter such a problem about exporting data to excel or word, especially excel.

I can export data to excel from gridview, but i can not apply styles to the excel cell. Last week, i found how to set the style.

For example:

the following is from:http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook
   xmlns="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:o="urn:schemas-microsoft-com:office:office"
   xmlns:x="urn:schemas-microsoft-com:office:excel"
   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
    <Author>Darl McBride</Author>
    <LastAuthor>Bill Gates</LastAuthor>
    <Created>2007-03-15T23:04:04Z</Created>
    <Company>SCO Group, Inc.</Company>
    <Version>11.8036</Version>
  </DocumentProperties>
  <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <WindowHeight>6795</WindowHeight>
    <WindowWidth>8460</WindowWidth>
    <WindowTopX>120</WindowTopX>
    <WindowTopY>15</WindowTopY>
    <ProtectStructure>False</ProtectStructure>
    <ProtectWindows>False</ProtectWindows>
  </ExcelWorkbook>
  <Styles>
    <Style ss:ID="Default" ss:Name="Normal">
      <Alignment ss:Vertical="Bottom" />
      <Borders />
      <Font />
      <Interior />
      <NumberFormat />
      <Protection />
    </Style>
    <Style ss:ID="s21">
      <Font x:Family="Swiss" ss:Bold="1" />
    </Style>
  </Styles>
  <Worksheet ss:Name="Sheet1">
    <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="5"
    x:FullColumns="1" x:FullRows="1">
      <Row>
        <Cell>
          <Data ss:Type="String">Text in cell A1</Data>
        </Cell>
      </Row>
      <Row>
        <Cell ss:StyleID="s21">
          <Data ss:Type="String">Bold text in A2</Data>
        </Cell>
      </Row>
      <Row ss:Index="4">
        <Cell ss:Index="2">
          <Data ss:Type="Number">43</Data>
        </Cell>
      </Row>
      <Row>
        <Cell ss:Index="2" ss:Formula="=R[-1]C/2">
          <Data ss:Type="Number">21.5</Data>
        </Cell>
      </Row>
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
      <Print>
        <ValidPrinterInfo />
        <HorizontalResolution>600</HorizontalResolution>
        <VerticalResolution>600</VerticalResolution>
      </Print>
      <Selected />
      <Panes>
        <Pane>
          <Number>3</Number>
          <ActiveRow>5</ActiveRow>
          <ActiveCol>1</ActiveCol>
        </Pane>
      </Panes>
      <ProtectObjects>False</ProtectObjects>
      <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
  </Worksheet>
</Workbook>

And i found a open source project http://excelpackage.codeplex.com/ which can easily create ooxml.

The same as excel, we can export data to word:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument
   xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"
   xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint"
   xmlns:o="urn:schemas-microsoft-com:office:office"
   w:macrosPresent="no"
   w:embeddedObjPresent="no"
   w:ocxPresent="no"
   xml:space="preserve">
  <o:DocumentProperties>
    <o:Title>This is the title</o:Title>
    <o:Author>Darl McBride</o:Author>
    <o:LastAuthor>Bill Gates</o:LastAuthor>
    <o:Revision>1</o:Revision>
    <o:TotalTime>0</o:TotalTime>
    <o:Created>2007-03-15T23:05:00Z</o:Created>
    <o:LastSaved>2007-03-15T23:05:00Z</o:LastSaved>
    <o:Pages>1</o:Pages>
    <o:Words>6</o:Words>
    <o:Characters>40</o:Characters>
    <o:Company>SCO Group, Inc.</o:Company>
    <o:Lines>1</o:Lines>
    <o:Paragraphs>1</o:Paragraphs>
    <o:CharactersWithSpaces>45</o:CharactersWithSpaces>
    <o:Version>11.6359</o:Version>
  </o:DocumentProperties>
  <w:fonts>
    <w:defaultFonts
       w:ascii="Times New Roman"
       w:fareast="Times New Roman"
       w:h-ansi="Times New Roman"
       w:cs="Times New Roman" />
  </w:fonts>
  <w:styles>
    <w:versionOfBuiltInStylenames w:val="4" />
    <w:latentStyles w:defLockedState="off" w:latentStyleCount="156" />
    <w:style w:type="paragraph" w:default="on" w:styleId="Normal">
      <w:name w:val="Normal" />
      <w:rPr>
        <wx:font wx:val="Times New Roman" />
        <w:sz w:val="24" />
        <w:sz-cs w:val="24" />
        <w:lang w:val="EN-US" w:fareast="EN-US" w:bidi="AR-SA" />
      </w:rPr>
    </w:style>
    <w:style w:type="paragraph" w:styleId="Heading1">
      <w:name w:val="heading 1" />
      <wx:uiName wx:val="Heading 1" />
      <w:basedOn w:val="Normal" />
      <w:next w:val="Normal" />
      <w:rsid w:val="00D93B94" />
      <w:pPr>
        <w:pStyle w:val="Heading1" />
        <w:keepNext />
        <w:spacing w:before="240" w:after="60" />
        <w:outlineLvl w:val="0" />
      </w:pPr>
      <w:rPr>
        <w:rFonts w:ascii="Arial" w:h-ansi="Arial" w:cs="Arial" />
        <wx:font wx:val="Arial" />
        <w:b />
        <w:b-cs />
        <w:kern w:val="32" />
        <w:sz w:val="32" />
        <w:sz-cs w:val="32" />
      </w:rPr>
    </w:style>
    <w:style w:type="character" w:default="on" w:styleId="DefaultParagraphFont">
      <w:name w:val="Default Paragraph Font" />
      <w:semiHidden />
    </w:style>
    <w:style w:type="table" w:default="on" w:styleId="TableNormal">
      <w:name w:val="Normal Table" />
      <wx:uiName wx:val="Table Normal" />
      <w:semiHidden />
      <w:rPr>
        <wx:font wx:val="Times New Roman" />
      </w:rPr>
      <w:tblPr>
        <w:tblInd w:w="0" w:type="dxa" />
        <w:tblCellMar>
          <w:top w:w="0" w:type="dxa" />
          <w:left w:w="108" w:type="dxa" />
          <w:bottom w:w="0" w:type="dxa" />
          <w:right w:w="108" w:type="dxa" />
        </w:tblCellMar>
      </w:tblPr>
    </w:style>
    <w:style w:type="list" w:default="on" w:styleId="NoList">
      <w:name w:val="No List" />
      <w:semiHidden />
    </w:style>
  </w:styles>
  <w:docPr>
    <w:view w:val="print" />
    <w:zoom w:percent="100" />
    <w:doNotEmbedSystemFonts />
    <w:proofState w:spelling="clean" w:grammar="clean" />
    <w:attachedTemplate w:val="" />
    <w:defaultTabStop w:val="720" />
    <w:punctuationKerning />
    <w:characterSpacingControl w:val="DontCompress" />
    <w:optimizeForBrowser />
    <w:validateAgainstSchema />
    <w:saveInvalidXML w:val="off" />
    <w:ignoreMixedContent w:val="off" />
    <w:alwaysShowPlaceholderText w:val="off" />
    <w:compat>
      <w:breakWrappedTables />
      <w:snapToGridInCell />
      <w:wrapTextWithPunct />
      <w:useAsianBreakRules />
      <w:dontGrowAutofit />
    </w:compat>
  </w:docPr>
  <w:body>
    <wx:sect>
      <w:p>
        <w:r>
          <w:t>This is the first paragraph</w:t>
        </w:r>
      </w:p>
      <wx:sub-section>
        <w:p>
          <w:pPr>
            <w:pStyle w:val="Heading1" />
          </w:pPr>
          <w:r>
            <w:t>This is a heading</w:t>
          </w:r>
        </w:p>
        <w:sectPr>
          <w:pgSz w:w="12240" w:h="15840" />
          <w:pgMar w:top="1440"
		   w:right="1800"
		   w:bottom="1440"
		   w:left="1800"
		   w:header="720"
		   w:footer="720"
		   w:gutter="0" />
          <w:cols w:space="720" />
          <w:docGrid w:line-pitch="360" />
        </w:sectPr>
      </wx:sub-section>
    </wx:sect>
  </w:body>
</w:wordDocument>

If we want to export some complex data to excel, we can create the xml manually, apply every style we like we want

Posted: Mar 04 2009, 02:14 PM by Ralax | with 1 comment(s)
Filed under: , , ,
SQL 表信息问题

若要查看表的列名,可以使用 sp_help 或下列查询之一:SELECT name FROM sys.columns WHERE OBJECT_ID IN (SELECT OBJECT_ID ('table_name')) 或 SELECT TOP 0 * FROM table_name。
1.   Execute sp_help tablename  如: Execute sp_help 'Schedule'
2.   Select Top 0 * From tablename 如:Select Top 0 * From 'Schedule'
3.   Select name From sys.columns where Object_Id In (Select Object_Id(tablename)) 如: Select name From sys.columns where Object_Id In (Select Object_Id('Schedule'))
三种的区别如下:
1.   可以得到table的详细信息,可以得到五个表
2.   一个无记录行的表结构
3.   一个单列表,列名name,内容是表的列名称

Posted: Nov 28 2008, 07:54 PM by Ralax | with no comments
Filed under: ,
How to invoke PageMethods in MasterPage
I have a web project, in the project, there is a MasterPage and some WebContentPages.
In the MasterPage, there is a function, when you click a button, show or hide the left content.When you refresh or navigate other WebContentPage, the left content keeps its display style.
Here is my first solution:
MasterPage.Master:

<div id="left" style='<%=string.Format("display:{0}",GetToolbarDisplayFlag())%>'>

</div>

<div id="buttons_left">
     <img alt="Move Left" onclick="switchView('left',this);" src='<%=GetImgSrc()%>' />

</div>

Remember to set the EnablePageMethods = "True"


MasterPage.Master.CS:

public string GetToolbarDisplayFlag()
{

       return HttpContext.Current.Session["ToolbarDisplay"] == null ? "block" : HttpContext.Current.Session["ToolbarDisplay"].ToString();

}
public string GetImgSrc()
{
   if(GetToolbarDisplayFlag() == string.Empty || GetToolbarDisplayFlag() == "block")
   {
       return "../App_Themes/images/s_left.gif";
   }
   return "../App_Themes/images/s_right.gif";

}

[WebMethod]public static void SetToolbarDisplayFlag(string flag)
{
    HttpContext.Current.Session["ToolbarDisplay"= flag;

}


JS:


function switchView(objname,current)
{
    var obj = $get(objname);
    if(obj.style.display=="block" || obj.style.display=="")
    {
        obj.style.display="none";
        current.src ='../App_Themes/images/s_right.gif';
        PageMethods.SetToolbarDisplayFlag("none",OnSucceeded,OnFailed);
    }
    else
    {
        obj.style.display="block";
        current.src ='../App_Themes/images/s_left.gif';
        PageMethods.SetToolbarDisplayFlag("block",OnSucceeded,OnFailed);
    }
}
function OnSucceeded(result, userContext, methodName)
{   
    return;
} 
function OnFailed(error, userContext, methodName)
{
    return;
}           

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


When you click the button, it will cause exception: PageMethods not defined.

This is because the method "SetToolbarDisplayFlag" Js invoke is in MasterPage, it seems PageMethods donot contain MasterPage methods.

 

So, my solution is move the method "SetToolbarDisplayFlag" from MasterPage to a base page called "PageBase" which inherited from System.Web.UI.Page, and each WebContentPage derived from PageBase.

PageBase.cs:


public class PageBase : Page

{

   [WebMethod]
   public static void SetToolbarDisplayFlag(string flag)
   {
       HttpContext.Current.Session["ToolbarDisplay"] = flag;

   }

}


Now, you can invoke methods in MasterPage.
Posted: Nov 13 2008, 07:51 PM by Ralax | with 6 comment(s)
Filed under: , , , ,
ModelPopupExtender的一个问题解决方案

      最近用ModelPopupExtender时,总是提示我有 Sys.InvalidOperationException 未通过 Sys.UI.DomEvent.addHandler 的错误,后来发现是我设置了CancellControlID,而没有设置相应的事件,我是通过在服务器端Show和Hide来控制的,这样脚本在寻找CancellControlID的时候就找不到了,就为null,在脚本中就会抛出以上错误。所以,如果我们要在服务器端控制ModelPopupExtender,不要设置ControlId就可以了!

Posted: Nov 07 2008, 11:22 PM by Ralax | with 2 comment(s)
Filed under: , , , ,
Asp.Net Web开发需要了解的知识

       很久没有做Web开发了,本以为有以前的基础加上WinForm的开发经验,Web应该不是什么问题的,应该很Easy。但是现在我发现我错了,Web开发已经不是简单的事情了。现在Web开发出来的一些优秀产品已经比较接近WinForm了,这就提高了Web开发的门槛。所以,现在如果我们想做好Web的开发,至少应该了解以下几方面的开发知识:

  • Asp.Net
  • Asp.Net Ajax
  • Asp.Net Ajax Client Library
  • Asp.Net Ajax Future Controls and Ajax Controls Toolkit
  • Javascript
  • Css
  • WebStandard
  • XML/XHTML/HTML
  • Regular Expression
  • JSON Service(Soap)
  • Silverlight
  • Third party product, for example JQuery, Ajax Pro

了解以上东西也并不代表就能做好Web开发,怎么灵活运用这些知识,深入发掘他们之间的交互才是最重要的东西。看来Web开发的路,我还要学习很久啊!

Posted: Nov 06 2008, 08:45 PM by Ralax | with 2 comment(s)
Filed under: , ,
A question about Page Header

When you add a Literal control to Page Header, for example:

<head runat="server">
    <asp:Literal runat="server" ID ="literal" >Literal Test!</asp:Literal>
     <title>Untitled Page</title>
</head>

When you browser the page, you will find "Literal Test!" was displayed.

View the source code:
<head>
    Literal Test!
     <title>
          Untitled Page
     </title>
</head>

but if you use Developer Toolbar or Doc Inspector of FF, the source code is different:
<head>
    <title>
         Untitled Page
    </title>
</head>
<body>
   Literal Test!

  ......

</body>

I don't understand, anyone can tell me which is right and why they are different? thanks!
Posted: Oct 02 2008, 04:45 PM by Ralax | with 3 comment(s)
Filed under: ,
单例模式

从今天开始,我每周会写一个关于设计模式的文章,还是用自己的语言,从自己的角度来阐述设计模式的用途,好处,以及怎么用。

首先,最简单的也就是单例了,我就用他作为自己的第一篇设计模式的文章吧。

1. 单例的目的是什么?  
   
这个应该很明显,保证一个类只有单一的实例,也就是说你无法通过New或CreateInstance来创建这个类的一个新实例。
2. 单例的好处在哪里?
   
当一个对象在程序内部只能有一个实例的时候,它可以保证我们不会重复创建,而是始终指向同一个对象。
3. 怎么用?
     单例模式的实现代码如下:

namespace SinglePattern
{
     public class SingleClass
     {
         private static SingleClass instance;

         protected SingleClass(){}

         public static SingleClass GetInstance()
         {
             if(instance == null)
             {
                 instance = new SingleClass();
             }
             return instance;
         }

}
}

上面的代码,可以说是一个标准的单例的代码,但是上述代码在多线程的时候有可能会产生多个实例,为了避免这个情况的发生,我们需要限制同一时间,只能有一个线程访问。

利用lock可以实现我们的目的:

namespace SinglePattern
{
     public class SingleClass
     {
         // 静态变量
         private static SingleClass instance;

         // "锁"变量
         private static object lockObject = new objest();

         // 受保护的构造函数
         protected SingleClass(){}

         // 静态获取对象的方法
         public static SingleClass GetInstance()
         {
             lock (lockObject)
             {
                 if (instance == null)
                 {
                     instance = new SingleClass();
                 }
             }
             return instance;
         }

     }
}

另一个方法:

这个方法经过调整之后,也可以用于限制一个窗体只能启动一个实例。

using System.Threading;
namespace SinglePattern
{
     public class SingleClass
     {
         // 静态变量
         private static SingleClass instance;

         // 受保护的构造函数
         protected SingleClass(){}

// 静态获取对象的方法
         public static SingleClass GetInstance()
         {
Mutex mutex = new Mutex();
             mutex.WaitOne();

             if (instance == null)
             {
                 instance = new SingleClass();
             }

             mutex.Close();

             return instance;
         }

     }
}

Posted: Feb 03 2008, 03:12 PM by Ralax | with no comments
Filed under:
More Posts Next page »