C # timed to perform tasks

Source: Internet
Author: User
Tags serialization

Start a timed task when the Web program starts, apply a pool recycle, or start a scheduled task again after the program shuts down, and continue execution on its original basis (using serialization to save its persistence)

The timed Task object is serialized into the database, and then retrieved from the database to be used as an instance object.

serialization, deserialization of object instances, byte[] conversion methods:

<summary>///serialization of a class instance object///</summary>///<param name= "obj" > class instance Object </param>///<returns& gt; serialized byte array </returns> public static byte[] Classserializer (object obj) {//Create a memory stream MemoryStream stream = new Memor Ystream (); Instantiate binary sequence class iformatter BF = new BinaryFormatter (); Serializes the given class instance object to the specified stream BF. Serialize (stream, obj); Reads the contents of the stream into the byte[] object byte[] info = new Byte[stream. Length]; Stream. Position = 0; Stream. Read (info, 0, (int) stream. Length); Turn off stream streams. Close (); Returns the serialized byte array return info; ///<summary>///Deserialization stream builds a new object///</summary>///<param name= "info" > serialized byte array </param>///&L t;returns></returns> public static Object Classdeserialize (byte[] info) {//create a memory stream initialized with a specified byte[] MemoryStream stream = new MemoryStream (info); Instantiate binary sequence class iformatter BF = new BinaryFormatter (); Deserializes the data in the stream, generating a new object obj = bf. Deserialize (stream); Turn off stream streams. Close (); Returns the object returned obj that was generated after deserialization; }

Base timed Task Action class:

namespace _66_timertask {//This class of serializable [Serializable] public class Timerinfo {//Define delegate class public delegate void Timertaskdelegate ( ); The current executing program name is public string name = ""; After a few seconds to perform the task public int second; Define delegate instance private timertaskdelegate fun; The definition of a thread//thread is not serializable [nonserialized] private thread t; <summary>///Constructor///</summary>///<param name= "name" > Thread name </param>///<param "sec Ond > seconds to perform Tasks </param>///<param name= "Fun" > Tasks to perform </param> public timerinfo (string name, int Second, timertaskdelegate fun) {this.name = name; This.second = second; this.fun = fun;}///<summary>///start timed tasks </summary> public void Star () {t = new Thread (newthreadstar); t.name = THIS.name; T.start ();}///<summary& Gt Recursive invocation realizes loop Newthreadstar (); ///<summary>///Terminate timed task///</summary> public void Abort () {if (t!= null) {T.abort ();}} } }

method to call a timed task:

namespace _66_timertask.delegatefunction {[Serializable] public class Delegatefun {///<summary>///test method/// ;/summary> public static void Test1 () {SqlConnection con = new SqlConnection ("Data source=.;i Nitial catalog=globechineseclubv1.1; Uid=sa; Pwd= "); Con. Open (); SqlCommand cmd = new SqlCommand ("INSERT into timertest (time) VALUES (' + DateTime.Now + ')", con); Cmd. ExecuteNonQuery (); Con. Close (); public static void Test2 () {SqlConnection con = new SqlConnection ("Data source=.;i Nitial catalog=globechineseclubv1.1; Uid=sa; Pwd= "); Con. Open (); SqlCommand cmd = new SqlCommand ("INSERT into TimerTest2 (time) VALUES (' + DateTime.Now + ')", con); Cmd. ExecuteNonQuery (); Con. Close (); } } }

Test (Global.asax):

Timerinfo T1; void Application_Start (object sender, EventArgs e) {//code to run at application startup Createtimer ();//create timed task private void Createtimer () {#region Check to see if the database has a serialized related class instance object stored, or, if so, the query database specifies the field, deserialized to the specified instance object: T1 = (timerinfo) serializationhelper.classdeserialize ( (byte[]) sdr["info"]; Does not exist, create a new Timerinfo instance object: T1 = new _66_timertask.timerinfo (uncreatetimersname [i], 10, _66_ TIMERTASK.DELEGATEFUNCTION.DELEGATEFUN.TEST1); Start timed Task T1 #endregion//. Star (); } void Application_End (object sender, EventArgs e) {//serializing the specified instance object when the application shuts down, returning its byte[] byte[] Info1 = Serializationhel Per. Classserializer (t1); SqlConnection con = new SqlConnection (CONNECTIONSTR); Con. Open (); Byte[after serializing the object] writes the database info field (image type) SqlCommand cmd = new SqlCommand ("Delete Timerinfotest;insert into Timerinfotest" ( Classname,info) VALUES (' + T1.name + "', @info)", con); Cmd. Parameters.Add ("@info", System.Data.SqlDbType.Binary); Cmd. parameters["@info"]. Value = Info1; Cmd. ExecuteNonQuery (); Con. Close (); }

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.