How to return data from void function?

女生的网名这么多〃 提交于 2019-12-06 10:08:37

You can use events (which implement the Observable pattern) to alert any listener that a new message has arrived:

public class NewMessageArgs : EventArgs
{
    public string Message { get; private set; }

    public NewMessageArgs(string message)
    {
        Message = message;
    }
}

public class ActiveXComponent
{
    public event EventHandler<NewMessageArgs> OnMessage;


    public void StartThread()
    {
        while (true)
        {
            //do stuff

            //raise "message received" event
            if (OnMessage != null)
                OnMessage(this, new NewMessageArgs("hi"));
        }
    }
}

You can then listen to these events like so:

ActiveXComponent activex = new ActiveXComponent();
activex.OnMessage += ProcessMessage;
activex.StartThread();

public void ProcessMessage(object sender, NewMessageArgs args)
{
    var msg = args.Message;
    //process
}

Basically you have to store some data in a spot where you can access it from both places (from the thread, and from the place where you started the thread). So you have a couple of options from the top of my head.

  1. Store it in a database
  2. Create a specific object (whatever type you need), and store it in a place where it is accessible from both places. For example, a singleton. A simpler better solution is to create a property on your ClassLibrary.Class1 class: set it from within the Class1-class, and get it from the place where you created an instance of your Class1-class.
  3. Add an event to your Class1-class which fires when it is finished doing its job. And add some data to the EventArgs.

I'm assuming here you get notified when your thread is done doing whatever it is doing.

Edit: added events

The threading function can change the fields values of the class and you can access those fields, also your thread can fire events that other classes can subcribe to and then act on it.

Class1
{
 private string value;
 public string Value{get{return value;} set{value=value; FireTheEvent();}}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!