クロススレッド操作は無効です:コントロールが作成されたスレッド以外のスレッドからアクセスされる

StackOverflow https://stackoverflow.com/questions/142003

質問

シナリオがあります。(Windows フォーム、C#、.NET)

  1. いくつかのユーザー コントロールをホストするメイン フォームがあります。
  2. ユーザー コントロールは、大量のデータ操作を実行します。たとえば、 UserControl_Load メソッドのロード メソッドの実行中、UI が応答しなくなります。
  3. これを克服するために、別のスレッドにデータをロードします(既存のコードの変更をできるだけ少なくしようとします)
  4. データをロードし、完了するとアプリケーションに作業が完了したことを通知するバックグラウンド ワーカー スレッドを使用しました。
  5. ここで本当の問題が発生しました。すべての UI (メイン フォームとその子ユーザー コントロール) はプライマリ メイン スレッドで作成されました。ユーザーコントロールの LOAD メソッドでは、ユーザーコントロール上のいくつかのコントロール (テキストボックスなど) の値に基づいてデータをフェッチしています。

疑似コードは次のようになります。

コード1

UserContrl1_LoadDataMethod()
{
    if (textbox1.text == "MyName") // This gives exception
    {
        //Load data corresponding to "MyName".
        //Populate a globale variable List<string> which will be binded to grid at some later stage.
    }
}

それが与えた例外は

クロススレッド操作は無効です:コントロールが作成されたスレッド以外のスレッドからアクセスされました。

これについて詳しく知るために、グーグルで調べてみたところ、次のコードを使用するような提案が出てきました。

コード2

UserContrl1_LoadDataMethod()
{
    if (InvokeRequired) // Line #1
    {
        this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
        return;
    }

    if (textbox1.text == "MyName") // Now it wont give an exception
    {
    //Load data correspondin to "MyName"
        //Populate a globale variable List<string> which will be binded to grid at some later stage
    }
}

でもでもでも...振り出しに戻ったようだ。アプリケーションは再び反応しません。1行目のif条件の実行が原因と思われます。読み込みタスクは、私が生成した 3 番目のスレッドではなく、親スレッドによって再び実行されます。

私がこれを正しいと認識したかどうかはわかりません。スレッド作成は初めてです。

これを解決するにはどうすればよいですか?また、Line#1 if ブロックの実行による影響は何ですか?

状況はこれです:コントロールの値に基づいてデータをグローバル変数にロードしたいと考えています。子スレッドからコントロールの値を変更したくありません。子スレッドからは絶対にやりません。

したがって、値にアクセスするだけで、対応するデータをデータベースから取得できます。

役に立ちましたか?

解決

とおり Prera​​k K の更新コメント (削除後):

質問が適切に提示されていないと思います。

状況は次のとおりです。コントロールの値に基づいてデータをグローバル変数にロードしたいと考えています。子スレッドからコントロールの値を変更したくありません。子スレッドからは絶対にやりません。

したがって、値にアクセスするだけで、対応するデータがデータベースから取得されます。

必要なソリューションは次のようになります。

UserContrl1_LOadDataMethod()
{
    string name = "";
    if(textbox1.InvokeRequired)
    {
        textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
    }
    if(name == "MyName")
    {
        // do whatever
    }
}

本格的な処理は別スレッドで行ってください 前に コントロールのスレッドに戻ろうとします。例えば:

UserContrl1_LOadDataMethod()
{
    if(textbox1.text=="MyName") //<<======Now it wont give exception**
    {
        //Load data correspondin to "MyName"
        //Populate a globale variable List<string> which will be
        //bound to grid at some later stage
        if(InvokeRequired)
        {
            // after we've done all the processing, 
            this.Invoke(new MethodInvoker(delegate {
                // load the control with the appropriate data
            }));
            return;
        }
    }
}

他のヒント

UIのスレッドモデル

スレッドモデル 基本的な概念を理解するためのUIアプリケーション。リンクは、WPFスレッドモデルを説明するページに移動します。ただし、Windows Formsは同じ考え方を利用しています。

UIスレッド

ここに画像の説明を入力

ここに画像の説明を入力

BeginInvokeおよびInvokeメソッド

ここに画像の説明を入力

呼び出す

ここに画像の説明を入力

BeginInvoke

画像の説明を入力	</div>
</div>
<div id=

UIを変更するために必要な最小限の作業のために、InvokeまたはBeginInvokeのみを使用します。あなたの「重い」メソッドは別のスレッドで(たとえば、BackgroundWorkerを介して)実行する必要がありますが、UIを更新するためだけにControl.Invoke / Control.BeginInvokeを使用します。そうすれば、UIスレッドはUIイベントなどを自由に処理できます。

スレッドの記事をご覧ください。 com /〜skeet / csharp / threads / winforms.shtml "rel =" noreferrer "> WinFormsの例-BackgroundWorkerが登場する前に記事が書かれていたので、更新していないのではないかと心配していますその点。 BackgroundWorkerは、コールバックを少しだけ単純化します。

FileSystemWatcher でこの問題が発生しましたが、次のコードで問題が解決したことがわかりました:

fsw.SynchronizingObject = this

コントロールは現在のフォームオブジェクトを使用してイベントを処理するため、同じスレッド上にあります。

今ではもう手遅れです。しかし、クロススレッドコントロールにアクセスできない場合は、今日でも?これは日付までの最短回答です:P

Invoke(new Action(() =>
                {
                    label1.Text = "WooHoo!!!";
                }));

これは、スレッドからフォームコントロールにアクセスする方法です。

.NETのコントロールは一般にスレッドセーフではありません。つまり、存在するスレッド以外のスレッドからコントロールにアクセスしないでください。これを回避するには、2番目のサンプルが試みているコントロールを呼び出す必要があります。

ただし、あなたの場合、実行したのはメインスレッドに長時間実行されるメソッドを渡すことだけです。もちろん、それは本当にあなたがやりたいことではありません。メインスレッドで行うことは、あちこちでクイックプロパティを設定するだけなので、これを少し再考する必要があります。

フォームに関連するすべてのメソッド内に散らかる必要があるチェックアンドインボークコードは、非常に冗長で不必要です。完全に廃止できる簡単な拡張メソッドを次に示します。

public static class Extensions
{
    public static void Invoke<TControlType>(this TControlType control, Action<TControlType> del) 
        where TControlType : Control
        {
            if (control.InvokeRequired)
                control.Invoke(new Action(() => del(control)));
            else
                del(control);
    }
}

そして、あなたは単にこれを行うことができます:

textbox1.Invoke(t => t.Text = "A");

これ以上いじらない-シンプル。

UIクロススレッドの問題に対する最もクリーンな(そして適切な)ソリューションは、SynchronizationContextを使用することです。マルチスレッドアプリケーションでのUI呼び出しの同期の記事では、非常にうまく説明しています。

Async / Awaitとコールバックを使用した新しい外観。プロジェクトで拡張メソッドを保持する場合、必要なコードは1行だけです。

/// <summary>
/// A new way to use Tasks for Asynchronous calls
/// </summary>
public class Example
{
    /// <summary>
    /// No more delegates, background workers etc. just one line of code as shown below
    /// Note it is dependent on the XTask class shown next.
    /// </summary>
    public async void ExampleMethod()
    {
        //Still on GUI/Original Thread here
        //Do your updates before the next line of code
        await XTask.RunAsync(() =>
        {
            //Running an asynchronous task here
            //Cannot update GUI Thread here, but can do lots of work
        });
        //Can update GUI/Original thread on this line
    }
}

/// <summary>
/// A class containing extension methods for the Task class 
/// Put this file in folder named Extensions
/// Use prefix of X for the class it Extends
/// </summary>
public static class XTask
{
    /// <summary>
    /// RunAsync is an extension method that encapsulates the Task.Run using a callback
    /// </summary>
    /// <param name="Code">The caller is called back on the new Task (on a different thread)</param>
    /// <returns></returns>
    public async static Task RunAsync(Action Code)
    {
        await Task.Run(() =>
        {
            Code();
        });
        return;
    }
}

Try / Catchステートメントでラップするなど、Extensionメソッドに他のものを追加できます。これにより、呼び出し元は、完了後に返す型、呼び出し元への例外コールバックを伝えることができます。

Try Catch、自動例外ログ、およびCallBackの追加

    /// <summary>
    /// Run Async
    /// </summary>
    /// <typeparam name="T">The type to return</typeparam>
    /// <param name="Code">The callback to the code</param>
    /// <param name="Error">The handled and logged exception if one occurs</param>
    /// <returns>The type expected as a competed task</returns>

    public async static Task<T> RunAsync<T>(Func<string,T> Code, Action<Exception> Error)
    {
       var done =  await Task<T>.Run(() =>
        {
            T result = default(T);
            try
            {
               result = Code("Code Here");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled Exception: " + ex.Message);
                Console.WriteLine(ex.StackTrace);
                Error(ex);
            }
            return result;

        });
        return done;
    }
    public async void HowToUse()
    {
       //We now inject the type we want the async routine to return!
       var result =  await RunAsync<bool>((code) => {
           //write code here, all exceptions are logged via the wrapped try catch.
           //return what is needed
           return someBoolValue;
       }, 
       error => {

          //exceptions are already handled but are sent back here for further processing
       });
        if (result)
        {
            //we can now process the result because the code above awaited for the completion before
            //moving to this statement
        }
    }

Backgroundworkerの例を見る必要があります:
http://msdn.microsoft.com/en-us/library /system.componentmodel.backgroundworker.aspx 特に、UIレイヤーとの対話方法。あなたの投稿に基づいて、これはあなたの問題に答えているようです。

別のスレッドのオブジェクトを変更する(私の意見では)最も単純な方法に従ってください:

using System.Threading.Tasks;
using System.Threading;

namespace TESTE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Action<string> DelegateTeste_ModifyText = THREAD_MOD;
            Invoke(DelegateTeste_ModifyText, "MODIFY BY THREAD");
        }

        private void THREAD_MOD(string teste)
        {
            textBox1.Text = teste;
        }
    }
}

xamarin stuidio以外のビジュアルスタジオwinformsプロトタイププロジェクトでiOS-Phoneモノタッチアプリコントローラーをプログラミングしているときに、この必要性を発見しました。可能な限りxamarinスタジオを介してVSでプログラミングすることを優先して、コントローラーを電話フレームワークから完全に切り離したいと考えました。これにより、AndroidやWindows Phoneなどの他のフレームワークにこれを実装することは、将来の使用のためにはるかに簡単になるでしょう。

すべてのボタンクリックの背後にあるクロススレッドスイッチングコードを処理する負担なしに、GUIがイベントに応答できるソリューションが必要でした。基本的に、クラスコントローラーにそれを処理させ、クライアントコードをシンプルに保ちます。 GUIで多くのイベントが発生する可能性があり、クラス内の1か所でイベントを処理できるようになります。私はマルチ・シーディングの専門家ではありません。これに欠陥がある場合はお知らせください。

public partial class Form1 : Form
{
    private ExampleController.MyController controller;

    public Form1()
    {          
        InitializeComponent();
        controller = new ExampleController.MyController((ISynchronizeInvoke) this);
        controller.Finished += controller_Finished;
    }

    void controller_Finished(string returnValue)
    {
        label1.Text = returnValue; 
    }

    private void button1_Click(object sender, EventArgs e)
    {
        controller.SubmitTask("Do It");
    }
}

GUIフォームは、コントローラーが非同期タスクを実行していることを認識していません。

public delegate void FinishedTasksHandler(string returnValue);

public class MyController
{
    private ISynchronizeInvoke _syn; 
    public MyController(ISynchronizeInvoke syn) {  _syn = syn; } 
    public event FinishedTasksHandler Finished; 

    public void SubmitTask(string someValue)
    {
        System.Threading.ThreadPool.QueueUserWorkItem(state => submitTask(someValue));
    }

    private void submitTask(string someValue)
    {
        someValue = someValue + " " + DateTime.Now.ToString();
        System.Threading.Thread.Sleep(5000);
//Finished(someValue); This causes cross threading error if called like this.

        if (Finished != null)
        {
            if (_syn.InvokeRequired)
            {
                _syn.Invoke(Finished, new object[] { someValue });
            }
            else
            {
                Finished(someValue);
            }
        }
    }
}

これは、このエラーを解決するための推奨される方法ではありませんが、すぐに抑制することができ、ジョブを実行します。プロトタイプやデモにはこれが好きです。追加

CheckForIllegalCrossThreadCalls = false

in Form1()コンストラクター。

作業中のオブジェクトにない場合の代替方法は次のとおりです

(InvokeRequired)

これは、メインフォームにあるがInvokeRequiredを持たないオブジェクトを使用して、メインフォーム以外のクラスでメインフォームを操作する場合に役立ちます

delegate void updateMainFormObject(FormObjectType objectWithoutInvoke, string text);

private void updateFormObjectType(FormObjectType objectWithoutInvoke, string text)
{
    MainForm.Invoke(new updateMainFormObject(UpdateObject), objectWithoutInvoke, text);
}

public void UpdateObject(ToolStripStatusLabel objectWithoutInvoke, string text)
{
    objectWithoutInvoke.Text = text;
}

上記と同じように機能しますが、invokerequiredを備えたオブジェクトはないが、MainFormにアクセスできる場合は、異なるアプローチです

前の回答と同じ行に沿って、 ただし、クロススレッド呼び出しの例外を発生させずにすべてのControlプロパティを使用できるようにする非常に短い追加です。

ヘルパーメソッド

/// <summary>
/// Helper method to determin if invoke required, if so will rerun method on correct thread.
/// if not do nothing.
/// </summary>
/// <param name="c">Control that might require invoking</param>
/// <param name="a">action to preform on control thread if so.</param>
/// <returns>true if invoke required</returns>
public bool ControlInvokeRequired(Control c, Action a)
{
    if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate
    {
        a();
    }));
    else return false;

    return true;
}

使用例

// usage on textbox
public void UpdateTextBox1(String text)
{
    //Check if invoke requied if so return - as i will be recalled in correct thread
    if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
    textBox1.Text = ellapsed;
}

//Or any control
public void UpdateControl(Color c, String s)
{
    //Check if invoke requied if so return - as i will be recalled in correct thread
    if (ControlInvokeRequired(myControl, () => UpdateControl(c, s))) return;
    myControl.Text = s;
    myControl.BackColor = c;
}
this.Invoke(new MethodInvoker(delegate
            {
                //your code here;
            }));

たとえば、UIスレッドのコントロールからテキストを取得するには:

Private Delegate Function GetControlTextInvoker(ByVal ctl As Control) As String

Private Function GetControlText(ByVal ctl As Control) As String
    Dim text As String

    If ctl.InvokeRequired Then
        text = CStr(ctl.Invoke(
            New GetControlTextInvoker(AddressOf GetControlText), ctl))
    Else
        text = ctl.Text
    End If

    Return text
End Function

同じ質問:how-to-update- the-gui-from-another-thread-in-c

2つの方法:

  1. e.resultの値を返し、それを使用してbackgroundWorker_RunWorkerCompletedイベントのyoutテキストボックスの値を設定します

  2. これらの種類の値を別のクラス(データホルダーとして機能します)に保持する変数を宣言します。このクラスの静的インスタンスを作成し、任意のスレッドを介してアクセスできます。

例:

public  class data_holder_for_controls
{
    //it will hold value for your label
    public  string status = string.Empty;
}

class Demo
{
    public static  data_holder_for_controls d1 = new data_holder_for_controls();
    static void Main(string[] args)
    {
        ThreadStart ts = new ThreadStart(perform_logic);
        Thread t1 = new Thread(ts);
        t1.Start();
        t1.Join();
        //your_label.Text=d1.status; --- can access it from any thread 
    }

    public static void perform_logic()
    {
        //put some code here in this function
        for (int i = 0; i < 10; i++)
        {
            //statements here
        }
        //set result in status variable
        d1.status = "Task done";
    }
}

アクションy; //クラス内で宣言

label1.Invoke(y =()=&gt; label1.Text =&quot; text&quot;);

単にこれを使用します:

this.Invoke((MethodInvoker)delegate
            {
                YourControl.Property= value; // runs thread safe
            });

クロススレッド操作には2つのオプションがあります。

Control.InvokeRequired Property 

2番目は

を使用することです
SynchronizationContext Post Method

Control.InvokeRequiredは、Controlクラスから継承されたコントロールを操作するときにのみ役立ちますが、SynchronizationContextはどこでも使用できます。いくつかの有用な情報は、リンクをたどる

クロススレッド更新UI | .Net

SynchronizationContextを使用したクロススレッド更新UI | .Net

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top