如何从void函数返回数据? [英] How to return data from void function?
问题描述
因此,大约一周前,我问了一个有关activex和UDP的问题.在这里:
So, around a week ago I asked a question about activex and UDP. Here it is:
现在,我创建了两个应用程序,一个(发送方)通过UDP发送预定义的字符串.另一个是从网页调用的activex组件,它的线程在后台运行. UDP消息到达后,就完成了它的工作(写在数据库中,写在log.txt中,等等).
Now, I created two applications, one (the sender) to send pre-defined strings via UDP. The other is activex component that is called from a webpage, and it's thread is working in the background. Once an UDP message arrives, then it's doing it's stuff (writing in database, writing in log.txt, and so on).
我需要做的最后一件事是返回数据(如果是字符串或其他形式,还需要说一说).但是,activex中被调用的方法必须为空,因为如果将其设为字符串,则该线程将无法工作,并且只有第一条消息会到达.
The last thing i need is to return data (it's yet to be said if it will be string or something else). However, the method in the activex which is called must be a void, because if it's made to be string, the threading wont work, and only the first message will arrive.
我的问题是,该怎么做?如何从void函数返回数据?例如,Web应用程序现在正在像这样调用activex DLL:
My question is, how to do that? How to return data from a void function? For example, the web app now is calling the activex DLL like this:
ClassLibrary1.Class1 activex = new ClassLibrary1.Class1();
activex.StartThread();
然后StartThread()调用侦听线程,并且它在后台工作,一旦UDP消息到达,它就会像我上面所说的那样做一些事情.
And the StartThread() calls the listening thread and it's working in the background, and once UDP msg arrives, its doing some stuff like i said above.
我如何通过线程(事件)返回值,然后Web应用程序将捕获并使用它?
How can i return value with the threads (events) and the web app will catch it and use it?
非常感谢.
推荐答案
您可以使用事件(实现了Observable模式)来提醒任何侦听器新消息已到达:
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
}
这篇关于如何从void函数返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!