【问题标题】:C# callback on new thread新线程上的 C# 回调
【发布时间】:2014-03-10 17:50:01
【问题描述】:

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

我有 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);
        }
    }
}

【问题讨论】:

  • API 对象在哪里实例化?
  • 不应该 startAttemptingWithUsername 是静态的吗?否则你必须先创建一个 Api 对象。
  • 包含在代码中
  • 为什么不赞成,详细说明会很好

标签: c# multithreading delegates


【解决方案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)));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多