0

enter code hereこのプロパティは .cs ファイルにあります。このプロパティを設定すると、それに関連付けられたイベントが発生します。

    public event Action ResponseReceived;
    private string response;

    public string Response
    {

        get
        {
            return response;
        }

        set
        {
                response = value;
                if (ResponseReceived != null) { ResponseReceived(); }
        }

    }

今問題は、私がそうするときに別のファイルにあるということです

ResponseReceived += new Action(function_ResponseReceived);
void function_ResponseReceived()
{
    //change to gui thread
    if (InvokeRequired) 
    {   
        this.BeginInvoke(new Action(function_ResponseReceived), new object[] { }); 
        return; 
    }

    textBox1.Text = Response;
}


Response = "yes";

. . . (いくつかの行の後) . . .

Response = "no";

しかし、常に発生yesするように、イベントに関連付けられた機能を起動しません(フィールドは、イベントを起動するのにかかる時間よりも速く更新されるため、上書きされると思います)。プロパティを設定したときに、イベントに関連付けられた関数が適切に起動する方法はありますかResponse = "no";Response

4

3 に答える 3

1

最初の答え:

あなたが示すコードは正常に動作します。
あなたが言及したコードには何かがなければなりません。. . (いくつかの行の後) . . .'.

テストコード:

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

namespace FunctionAssociatedPropertyFire {
    class Program {
        static void Main(string[] args) {
            new TestClass().Test();
            Console.ReadLine();
        }
    }
    class TestClass {
        public event Action ResponseReceived;
        private string response;    
        public string Response {
            get { return response; }    
            set {
                response = value;
                if (ResponseReceived != null) { ResponseReceived(); }
            }
        }

        void function_ResponseReceived() {
            Console.WriteLine("function_ResponseReceived");
        }

        public void Test() {
            ResponseReceived += new Action(function_ResponseReceived);
            Console.WriteLine("BeforeYes");
            Response = "yes";
            Console.WriteLine("AfterYes");
            Response = "no";
            Console.WriteLine("AfterNo");
        }
    }
}

テスト結果:

BeforeYes
function_ResponseReceived
AfterYes
function_ResponseReceived
AfterNo

アップデート:

非同期で呼び出しているため、呼び出し元のコードは、呼び出されたメソッドが終了するまで待機しません。BeginInvoke メソッドの代わりに Invoke メソッドの使用を試みることができます。

void function_ResponseReceived() {
    //change to gui thread
    if (InvokeRequired) 
    {   
        this.Invoke(new Action(function_ResponseReceived), new object[] { }); 
        return; 
    }

    textBox1.Text = Response;
}
于 2013-04-19T09:04:43.323 に答える