来自 DLL 的 C# 回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/288192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# callback from DLL
提问by
I'm writing Application A and DLL B, both in C#.NET. How do I do the following:
我正在用 C#.NET 编写应用程序 A 和 DLL B。我如何执行以下操作:
- A calls function in B
- Want B to use delegate/callback to update status in UI of A
- A 调用 B 中的函数
- 希望 B 使用委托/回调来更新 A 的 UI 中的状态
This is notabout BackgroundWorker...that part works fine in A. What I can't see is how to let B know what function to call in A.
这与 BackgroundWorker无关……那部分在 A 中工作正常。我看不到如何让 B 知道在 A 中调用什么函数。
回答by Rob Prouse
You have two options. The most common is to have an event in B and have your UI in A subscribe to that event. B then fires that event.
你有两个选择。最常见的是在 B 中有一个事件,并让 A 中的 UI 订阅该事件。B 然后触发该事件。
The second option is to pass in a delegate from A as a parameter to the method call in B. B can then Invoke that delegate.
第二个选项是将来自 A 的委托作为参数传递给 B 中的方法调用。然后 B 可以调用该委托。
回答by Brody
Pass in the callback object in the call A make to B. Use an interface (or tightly bound libraries). Make sure the callback object is thread aware and thread safe.
在调用 A make 到 B 时传入回调对象。使用接口(或紧密绑定的库)。确保回调对象是线程感知和线程安全的。
回答by Jeromy Irvine
To expand on Rob Prouse's answer, you need to declare a delegate and then pass a matching method into it.
要扩展 Rob Prouse 的答案,您需要声明一个委托,然后将匹配的方法传递给它。
In B:
在乙:
public delegate void CallbackDelegate(string status);
public void DoWork(string param, CallbackDelegate callback)
{
callback("status");
}
In A:
在一个:
public void MyCallback(string status)
{
// Update your UI.
}
And when you call the method:
当您调用该方法时:
B.DoWork("my params", MyCallback);
回答by Joel Coehoorn
If you control B, then Rob Prouse or Brody's answers will work fine.
如果您控制 B,那么 Rob Prouse 或 Brody 的答案将正常工作。
But what if you can't change B at all? In that case, you can always wrap a method in a delegate of your own making, as long it's signature matches that of the signature of the target method.
但是如果你根本不能改变 B 呢?在这种情况下,您始终可以将方法包装在您自己制作的委托中,只要它的签名与目标方法的签名相匹配。
So, say you have a class instance named B with a public method named b() (from the B dll assembly, of course). Class A in the A application can call it asynchronously like this:
因此,假设您有一个名为 B 的类实例,其中有一个名为 b() 的公共方法(当然来自 B dll 程序集)。A应用程序中的A类可以像这样异步调用它:
public class A
{
delegate void BDelegate();
public void BegineBMethod()
{
BDelegate b_method = new BDelegate(B.b);
b_method.BeginInvoke(BCallback, null);
}
void BCallback(IAsyncResult ar)
{
// cleanup/get return value/check exceptions here
}
}