首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 基礎建構塊 (一):Hello World、OpenFileDialog、COM 互通、多執行緒

     編輯:關於C語言

第一支 C# 程式:Hello World

// helloworld.cs
using System;

class Hello
{
    static void Main()
    {
        Console.WriteLine("Hello, C# World!");
    }
}

儲存為 helloworld.cs,命令列編譯:csc helloworld.cs,產生 helloworld.exe。

OpenFileDialog 開啟檔案對話方塊

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# 開啟檔案";
fdlg.InitialDirectory = @"c:\";
fdlg.Filter = "所有檔案 (*.*)|*.*|文字檔 (*.txt)|*.txt";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;

if (fdlg.ShowDialog() == DialogResult.OK)
{
    textBox1.Text = fdlg.FileName;
    // 可用 fdlg.OpenFile() 取得 Stream 讀取內容
}

呼叫 COM 元件:晚期繫結啟動 Excel

使用 System.Reflection 與 Activator.CreateInstance 透過 ProgID 建立 COM 物件,無需匯入型別程式庫(早期繫結)。

using System;
using System.Reflection;
using System.Threading;

class ComInteropDemo
{
    static void Main()
    {
        Type excelType = Type.GetTypeFromProgID("Excel.Application");
        if (excelType == null)
        {
            Console.WriteLine("未安裝 Excel");
            return;
        }

        object excel = Activator.CreateInstance(excelType);
        object[] param = new object[] { true }; // Visible = true

        try
        {
            excelType.InvokeMember("Visible",
                BindingFlags.SetProperty, null, excel, param);
            Console.WriteLine("Excel 已顯示,5 秒後關閉...");
            Thread.Sleep(5000);
        }
        catch (Exception ex)
        {
            Console.WriteLine("錯誤: " + ex.Message);
        }
        finally
        {
            // 釋放 COM 物件
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
        }
    }
}

建立多執行緒應用程式

核心類別在 System.Threading 命名空間。

基本操作

using System.Threading;

Thread thread = new Thread(new ThreadStart(WriteData));
thread.Start();           // 啟動
thread.Priority = ThreadPriority.Highest; // 設定優先權

// 暫停/繼續 (舊版 API,不建議新程式使用)
if (thread.ThreadState == ThreadState.Running) thread.Suspend();
if (thread.ThreadState == ThreadState.Suspended) thread.Resume();

// 終止
if (thread.IsAlive) thread.Abort(); // 強制終止,可能造成資源洩漏

// 延遲
Thread.Sleep(1000); // 目前執行緒睡眠 1 秒

執行緒方法範例

void WriteData()
{
    for (int i = 0; i <= 10000; i++)
    {
        string str = "Secondary Thread " + i;
        Console.WriteLine(str);
        // UI 更新需用 Invoke/BeginInvoke 回主執行緒
    }
}

現代最佳實務補充

  • Task/async-await:.NET 4.5+ 應優先使用 Task.Run、async/await,而非手動管理 Thread。
  • SynchronizationContext:UI 執行緒更新需透過 Control.Invoke (WinForms) 或 Dispatcher.Invoke (WPF)。
  • COM 釋放:使用 Marshal.ReleaseComObject,並搭配 GC.Collect()、GC.WaitForPendingFinalizers() 確保釋放。
  • OpenFileDialog:屬於 System.Windows.Forms,需參考對應組件。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved