Windows Mobile Development (iv)--retreat cultivation

Source: Internet
Author: User

long time not to write a blog, not because do not want to write, but recently more than the company's task, finally 11 have time to bubble up. Today we continue to introduce the most central priority in mobile development-memory management.C # code is managed code, C # programmers rarely like C/cpp programmers for the release of program resources, a c/cpp master must be a master of memory management, as a C # program does not require the same as the C/cpp programmer to manage memory resources, but the memory mechanism needs to have in-depth understanding, Those code resources are managed resources handed to the GC to process, those resources need to be manually released by the programmer, of course, people are more concerned about the unmanaged resources, because the managed resources GC will be automatically cleaned up.
Generally see if a class is a managed resource you can usually do this, in VS F12 go to the definition, see if the class or parent class implements the IDisposable interface, all classes that implement the IDisposable interface need to manually release resources, the GC will not clean these resources, in C # The common classes implemented in IDisposable interfaces are: Database connection parent class DbConnection and various database Adapter,command classes, various file streams, such as the parent class stream.
For these classes, we have two strategies. Strategy One:We use the try...catch...finally statement when we are using these classes to release resources in finally. The following are the specific practices:
public class sqlhelper{//Gets the database connection string in the configuration file private static readonly string connstr = Configurationmanager.connections trings["ConnStr"].        ConnectionString; <summary>////support for Universal Database parameter query method for stored procedure return DataTable///</summary>//<param name= "Sqlst R "> query SQL string </param>//<param name=" cmdtype "> Command type </param>///<param Name=" Paras "&G t; parameters </param>//<returns>datatable result set </returns> public static DataTable executedatatable ( String sqlstr, CommandType cmdtype, params sqlparameter[] paras) {//Create implement IDisposable interface class object Sql            DataAdapter adapter = null;                    try {adapter = new SqlDataAdapter (Sqlstr, connstr);                    DataTable dt = new DataTable ();                    Adapter.SelectCommand.CommandType = Cmdtype; IF (paras! = NULL && paras.                     Length > 0) {   Adapter.                    SelectCommand.Parameters.AddRange (paras); } adapter.            Fill (DT);//execute to this, adapter has run out of return DT;            } catch (Exception e) {//Log error log and other operations return null; finally {//releases the unmanaged resource adapter.            Dispose (); }        }

So, when we call SqlHelper'sof the Executedatatable methodtime, we do not have to care about the release of adapter object resources, finally statement will automatically release the resources when we run out of adapter, so although meet our requirements, but this seems a bit troublesome, good. Strategy Two:then use the C # using statement, as follows:       
public static DataTable executedatatable (String sqlstr, CommandType cmdtype, params sqlparameter[] paras)        {    // Implements the class object using of the IDisposable interface            (SqlDataAdapter adapter = new SqlDataAdapter (Sqlstr, connstr))            {                DataTable dt = New DataTable ();                Adapter.SelectCommand.CommandType = Cmdtype;                IF (paras! = NULL && paras. Length > 0)                {                    adapter. SelectCommand.Parameters.AddRange (paras);                }                Adapter. Fill (DT);                return dt;            }         }


It is better to write than to use a try. Finally convenient for many, as long as the using implementation of the IDisposable interface object, using the statement block IDisposable object will be automatically released, note that there is no implementation of Idispoable interface class is not to be using, In fact, using the internal is also try...catch...finally implementation, just Microsoft to encapsulate, this is the C # Programmer's proprietary syntax sugar.
Of course, if you also want to implement the IDisposable interface, can be used, then you refer to the Microsoft MSDN recommendations of the example, I do not have much ink here.
Say the unmanaged object, the managed object, the managed object is completely managed by the CLR's GC, so when does the GC reclaim the managed resources?
The so-called managed resources, there is no general class to implement the IDisposable interface, no files and database operations, such as int,string,list, etc., when we use these objects, we do not need to care about their release, they will be processed by the GC unified, In general, if the system memory is sufficient GC will not reclaim these managed resources, when the memory is tight when the GC reclaims those who do not have any references to the object, of course, C # also gives the programmer to manually invoke GC recycling method, GC. Collect () method, but even if the programmer calls the method manually, the GC does not necessarily recycle the managed resource at that moment, and the Collect () method does not recommend manual calls by the programmer, and if frequent calls can severely cripple the performance of the program, because memory is frequently recycled, C # There are three levels of garbage collection, want to know can Baidu a bit.
In the development of the website, often willing to sacrifice the appropriate memory to improve the performance of the site, because the memory of the speed of access far more than the speed of the disk, which will alleviate the pressure of the large concurrency of the site, so also produced a batch of memcached, Redis and other server memory management software, Even the MySQL database can store the data in memory, and of course the server restarts the memory data is generally not recoverable (Redis can be recovered), so what should be put into memory is the key to development.
As a mobile developer, the management of memory is very important. Because we do not have such a large amount of memory as the Web server, at present, I heard that the biggest memory is Microsoft Surface Pro3, this is the configuration of the tablet, but if it is a mobile phone? The biggest should be Xiaomi's 4th-generation mobile phone 3G memory, and then the current mainstream phone memory should be around 1.5G, Apple's cell phone memory to be smaller, in the face of such a small memory, programmers must grasp the use of memory when developing.
Since the cell phone memory is so small, is not that I put all the resources to use immediately after the release is good? This is the most resource-saving AH? Actually not, this depends on the specific needs to decide, in some cases we can put some common resources temporarily in memory, and so on again when using from memory call can greatly improve the speed of the program call, here we can use the framework of the thread pool principle, if the line constructor thread object, Constructor the object with a line, no new thread is opened.
There must be an important point of knowledge here. Even with weak references, the WeakReference class works by pointing the object at WeakReference and then placing the object as null (it can be recovered in time by GC discovery), We use the WeakReference object to directly use the object to point to, WeakReference will automatically manage the object, when the memory needs of the object, it is directly used, not in memory to create one, the use of the following methods:
Object obj = new object ();//objects are pointed by weak references         to weakreference wref = new WeakReference (obj);//Set object to null         obj = null;//Use weak reference Object Currobj=wref to. target;//use Currobj to complete business

About the weak reference to the simple introduction here, of course, the use of weak references is not only these, there are many, we can search their own, I do not introduce too much, in the later Windows Store application development I will specifically cite the specific application of weak references. If you want to deeply understand the use of memory, it is recommended to go online to see the Lu Jianzhong design mode video of the enjoy meta-mode, to enjoy the meta-mode is the sharing of memory, in fact, many things in development can be shared, in-depth understanding of the concept of pool is very important.
All right, here we are today, we'll see you next time.

Windows Mobile Development (iv)--retreat cultivation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.