我在我的智慧结束试图解决这个问题。需要帮助访问数据来自回调C#.NET
我有一个类中的功能,例如
public class ReceiveData
{
Dataprovider provider = new DataProvider();
public void ResponseData()
{
foreach(string anItem in TheList)
{
// AllData function is declared in class DataProvider
string result = provider.AllData(anItem);
}
//do something
}
}
这很简单。但是,如果AllData函数必须进行异步函数调用以获取数据,我该怎么办?
含义,说
public class DataProvider
{
MyServiceClient client = new MyServiceClient();
public string AllData (string myItem)
{
client.FormattedDataCompleted += new EventHandler<FormattedDataCompletedEventArgs>(client_FormattedDataCompleted);
client.FormattedDataAsync(myItem);
}
void client_FormattedDataCompleted(object sender, FormattedDataCompletedEventArgs e)
{
// here's where the response comes back.
}
正如你所看到的,现在我不能简单地调用ALLDATA功能,并直接找回数据。
那么,我需要做什么在ResponseData函数中确保我调用AllItem函数,并从回调中获取数据。请注意,该函数中有一个循环,所以我需要通过循环发送的所有参数都会得到相应的响应。
我尝试过的一种方法是使用AutoResetEvent类。
我将此处理程序定义为 AutoResetEvent handle = new AutoResetHandle(false);
然后我在async调用之后立即添加handle.WaitOne()。并在回调中添加了handle.Set();
但是,应用程序卡在handle.WaitOne()。所以我不明白为什么会发生这种情况。
我现在有一个理论上的想法,看看我是否可以在回调中使用事件提升器,并在RecieveData类中使用eventlistener,如果这两者沟通,我可以获取数据。但我花了一些时间尝试了解更多关于事件处理程序的知识,但还没有掌握它。
那么有没有人有任何其他的方法,想法?谢谢!
Sooo ...只是想了解...你想阻止请求的异步结果?你不想异步处理你的数据? – 2010-11-16 15:33:15
在球部分,是 – Qgalore 2010-11-16 18:26:49