次の方法で共有


CA2232: Windows フォームのエントリ ポイントを STAThread に設定します

TypeName

MarkWindowsFormsEntryPointsWithStaThread

CheckId

CA2232

[カテゴリ]

Microsoft.Usage

互換性に影響する変更点

なし

原因

アセンブリが System.Windows.Forms 名前空間を参照し、そのエンド ポイントが System.STAThreadAttribute 属性でマークされていません。

規則の説明

STAThreadAttribute は、アプリケーションの COM スレッド処理モデルがシングルスレッド アパートメントであることを示します。この属性は、Windows フォームを使用するすべてのアプリケーションのエントリ ポイントに指定する必要があります。省略すると、Windows コンポーネントが正常に機能しないことがあります。属性がない場合、アプリケーションではマルチスレッドのアパートメント モデルを使用します。このモデルは、Windows フォームでサポートされていません。

[!メモ]

アプリケーション フレームワークを使用する Visual Basic プロジェクトでは、Main メソッドを STAThread でマークする必要はありません。Visual Basic コンパイラで自動的に行われます。

違反の修正方法

この規則違反を修正するには、エントリ ポイントに STAThreadAttribute 属性を追加します。System.MTAThreadAttribute 属性がある場合、削除します。

警告を抑制する状況

STAThreadAttribute 属性が不要でサポートされていない、.NET Compact Framework 向けに開発している場合、この規則による警告を抑制しても安全です。

使用例

STAThreadAttribute の正しい使用方法を次の例に示します。

Imports System
Imports System.Windows.Forms

NameSpace UsageLibrary

Public Class MyForm
   Inherits Form

   Public Sub New()
      Me.Text = "Hello World!"
   End Sub 'New

   ' Satisfies rule: MarkWindowsFormsEntryPointsWithStaThread.
   <STAThread()> _
   Public Shared Sub Main()
      Dim aform As New MyForm()
      Application.Run(aform)
   End Sub

End Class

End Namespace
using System; 
using  System.Windows.Forms;

namespace UsageLibrary
{
    public class MyForm: Form
    {
        public MyForm()
        {
            this.Text = "Hello World!";
        }

        // Satisfies rule: MarkWindowsFormsEntryPointsWithStaThread.
        [STAThread]
        public static void Main()
        {
            MyForm aform = new MyForm();
            Application.Run(aform);
        }
    }
}