新线程上的C#回调

时间:2014-03-10 17:50:01

标签: c# multithreading delegates

我在新启动的线程上创建回调时遇到问题。

我有2个类,一个API和Form.cs.我从Form.cs开始在API中运行一个方法的线程,我想从API中的方法内部通知Form.cs中的方法。

我熟悉Obj-C中的委托,但不熟悉C#。

我只包含相关代码。

public partial class Main: Form
{

    private Api Connect = new Api();

    private void StartStopButton_Click(object sender, EventArgs e)
    {
        //new thread
        Thread ThreadConnect = new Thread(Connect.startAttemptingWithUsername);
        ThreadConnect.Start();
    }

    public void AttemptingWithPasswordMessage(string password)
    {
        // i want to notify this method from the API
    }
}

class Api : UserAgent
{
    public void startAttemptingWithUsername()
    {
        _shouldStop = false;
        while (!_shouldStop)
        {
            Console.WriteLine(username);
            // How would i notify AttemptingWithPasswordMessage from here?
            System.Threading.Thread.Sleep(1000);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

向您的其他班级提供一个活动,并根据处理情况在相关时触发该活动:

class Api : UserAgent
{
    public event Action<string> SomeEvent;//TODO give better name
    public void startAttemptingWithUsername()
    {
        _shouldStop = false;
        while (!_shouldStop)
        {
            Console.WriteLine(username);
            var handler = SomeEvent;
            if (handler != null)
                handler("asdf");
            // How would i notify AttemptingWithPasswordMessage from here?
            System.Threading.Thread.Sleep(1000);
        }
    }
}

然后为该事件添加一个处理程序:(并编组回UI线程)

private void StartStopButton_Click(object sender, EventArgs e)
{
    //new thread
    Thread ThreadConnect = new Thread(Connect.startAttemptingWithUsername);
    ThreadConnect.Start();
    Connect.SomeEvent += (data) => Invoke(
        new Action(()=>AttemptingWithPasswordMessage(data)));
}