为异步完成的事件处理程序传递附加变量
private void GeoCode_Method1(string myaddress, int waypointIndex, string callingUser)
{
GCService.GeocodeCompleted += new EventHandler<NSpace.GCService.GeocodeCompletedEventArgs>(GeoCode_Method1_GeocodeCompleted);
GCService.GeocodeAsync(request, waypointIndex);
}
void GeoCode_Method1_GeocodeCompleted(object sender, NSpace.GCService.GeocodeCompletedEventArgs e)
{
//***QUESTION: how do I access variable "callinguser" from GeoCode_Method1 in this method??
}
当我调用 GeoCode_Method1 时,我发送“callinguser”字符串变量,并且我想在 GeoCode_Method1_GeocodeCompleted 中访问它(异步 GeoCodingAsync 调用完成时触发)。我该怎么做?
private void GeoCode_Method1(string myaddress, int waypointIndex, string callingUser)
{
GCService.GeocodeCompleted += new EventHandler<NSpace.GCService.GeocodeCompletedEventArgs>(GeoCode_Method1_GeocodeCompleted);
GCService.GeocodeAsync(request, waypointIndex);
}
void GeoCode_Method1_GeocodeCompleted(object sender, NSpace.GCService.GeocodeCompletedEventArgs e)
{
//***QUESTION: how do I access variable "callinguser" from GeoCode_Method1 in this method??
}
When I call into GeoCode_Method1 I send in "callinguser" string variable, and i would like to access this in GeoCode_Method1_GeocodeCompleted (triggered when the async GeoCodingAsync call is done). How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是使用 C# lambda 表达式作为事件处理程序。然后,此 lambda 表达式可以调用
GeoCode_Method1_GeocodeCompleted
方法并传递callinguser
参数。The easiest way to do this is by using a C# lambda expression as the event handler. This lambda expression can then call into the
GeoCode_Method1_GeocodeCompleted
method and pass along thecallinguser
parameter.理想情况下,GCService 有一种方法可以为您处理该问题(如果它正确遵循异步事件模式,则应该如此),但如果没有,则可以使用 C# 闭包的方法,尽管它有点复杂。
您可以按照如下所示进行操作 - 在我的示例中,我展示了如何确保在事件完成时取消订阅 GeocodeCompleted 事件处理程序。
Ideally the GCService would have a way of handling that for you (it should if it properly followed the Async event pattern), but if it doesn't there is a way using C# closures, though it's a little complicated.
You'd do it as shown below - in my sample I've shown how you can make sure that the GeocodeCompleted event handler gets unsubscribed when the event is completed.
您应该创建一个 lambda 表达式:
lambda 表达式可以访问所有外部方法变量和参数。 (这称为 闭包)
lambda 表达式的
sender
和e
参数根据其所用作的委托类型隐式类型化。You should create a lambda expression:
The lambda expression can access all of the outer methods variables and parameters. (This is called a closure)
The lambda expression's
sender
ande
parameters are implicitly typed based on the delegate type it's being used as.