アットウィキロゴ

delegate

delegateの簡単な使い方

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public delegate string DelegateTest(string str1,string str2);

    class Program
    {
        static void Main(string[] args)
        {
            DelegateTest test = new DelegateTest(Join);
            Console.Write(test("明日は", "お休み!"));
            Console.Read();
        }

        private static string Join(string str1, string str2)
        {
            return str1 + str2;
        }
    }

}

出力結果
明日はお休み!


イベントとdelegate
ユーザコントロールを作ったりしたときに、その内部のコントロールのイベントを拾ったりするために使う。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public delegate void DelegateTest(string strMsg);

    class Program
    {
        static void Main(string[] args)
        {
            Sub subCls = new Sub();
            subCls.Str_Changed += Str_Changed;

            subCls.SetStr("");
        }

        protected static void Str_Changed(string strMsg)
        {
            Console.WriteLine(strMsg);
            Console.Read();
        }
    }

    class Sub
    {
        public event DelegateTest Str_Changed;

        private string Str;

        public void SetStr(string strMsg)
        {
            Str = strMsg;
            if (Str == "")
            {
                Str_Changed("空っぽ");
            }
        }
    }
}

出力結果
空っぽ

マルチスレッド
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread SubThread = new Thread(new ThreadStart(ThreadMethod));
            // スレッドの開始
            SubThread.Start();
            // 同期
            SubThread.Join();
            Console.Read();
        }

        private static void ThreadMethod()
        {
            int i = 0;
            while (i <= 10)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
                i++;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread SubThread = new Thread(new ThreadStart(ThreadMethod));
            // スレッドの開始
            SubThread.Start();
            // スレッドスリープ
            Thread.Sleep(1000);
            // スレッドの中断
            SubThread.Abort();
            Console.Read();
        }

        private static void ThreadMethod()
        {
            int i = 0;
            while (true)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
                i++;
            }
        }
    }
}

カウントダウン
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

    public partial class Form1 : Form
    {
        private System.Windows.Forms.Button btn;
        private System.Windows.Forms.TextBox txt;

        private Thread ThreadTest;
        private delegate void AddTextDelegate(string str);

        private static string[] strCaption = { "Start", "Stop", "Reset" };
        private BtnMode CurrentBtnMode;
        private [[enum]] BtnMode
        {
            Start = 0,
            Stop = 1,
            ReSet = 2
        }

        /// <summary>
        /// 必要なデザイナー変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 使用中のリソースをすべてクリーンアップします。
        /// </summary>
        /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
        protected override void Dispose(bool disposing)
        {
            // スレッドを終了させる
            ThreadTest.Abort();

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows フォーム デザイナーで生成されたコード

        /// <summary>
        /// デザイナー サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディターで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.btn = new System.Windows.Forms.Button();
            this.txt = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btn
            // 
            this.btn.Location = new System.Drawing.Point(12, 12);
            this.btn.Name = "btn";
            this.btn.Size = new System.Drawing.Size(75, 23);
            this.btn.TabIndex = 0;
            this.btn.Text = strCaption[(int)BtnMode.Start];
            this.btn.UseVisualStyleBackColor = true;
            // 
            // txt
            // 
            this.txt.Location = new System.Drawing.Point(12, 41);
            this.txt.Multiline = true;
            this.txt.Name = "txt";
            this.txt.Size = new System.Drawing.Size(268, 213);
            this.txt.TabIndex = 1;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.txt);
            this.Controls.Add(this.btn);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            this.btn.Click += this.btn_Click;

            CurrentBtnMode = BtnMode.Start;

            ThreadTest = new Thread(new ThreadStart(ThreadMethod));
            ThreadTest.Start();
        }

        protected void btn_Click(object sender, EventArgs e)
        {
            switch (CurrentBtnMode){
                case BtnMode.Start:
                    btn.Text = strCaption[(int)BtnMode.Stop];
                    CurrentBtnMode = BtnMode.Stop;
                    break;
                case BtnMode.Stop:
                    btn.Text = strCaption[(int)BtnMode.Start];
                    CurrentBtnMode = BtnMode.Start;
                    break;
                case BtnMode.ReSet:
                    btn.Text = strCaption[(int)BtnMode.Start];
                    CurrentBtnMode = BtnMode.Start;
                    ThreadTest = new Thread(new ThreadStart(ThreadMethod));
                    ThreadTest.Start();
                    break;
                default:
                    break;
            }
        }

        private void ThreadMethod()
        {
            int i = 100;
            while (i > 0)
            {
                while (CurrentBtnMode == BtnMode.Start)
                {
                    Thread.SpinWait(10);
                }
                Thread.Sleep(100);
                AddText(i.ToString());
                i--;
            }
            CurrentBtnMode = BtnMode.ReSet;
            AddText("完了!");
        }

        private void AddText(string str)
        {
            if (InvokeRequired)
            {
                AddTextDelegate dlg = new AddTextDelegate(AddText);
                this.Invoke(dlg, new object[] { str });
            }
            else
            {
                txt.AppendText(string.Format("{0}\n", str));
                if (CurrentBtnMode == BtnMode.ReSet)
                {
                    btn.Text = strCaption[(int)BtnMode.ReSet];
                }
            }
        }
    }
}




最終更新:2011年06月14日 00:46
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。