I have a limited understanding of aysnc so apologies if this is basic.
I'm using the Lync SDK to query contacts in my method, the SDK uses async to perform the search and returns the results fine to my call back.
I'd like to have my method SearchForContact not return to its caller under all the results have been obtained but I have no idea how to do this.
Thanks.
public void SearchForContact(string search)
{
var searchFields = _LyncClient.ContactManager.GetSearchFields();
object[] _asyncState = { _LyncClient.ContactManager, search };
_LyncClient.ContactManager.BeginSearch(search, SearchProviders.GlobalAddressList | SearchProviders.ExchangeService
, searchFields
, SearchOptions.Default
, 10
, result =>
{
searchForContactResults = new List<MeetingContact>();
SearchResults results = null;
results = ((ContactManager)_asyncState[0]).EndSearch(result);
if(results == null)
return;
MeetingContact contactResult = new MeetingContact();
foreach (var searchResult in results.AllResults)
{
var c = searchResult.Result as Contact;
contactResult.FullName = c.GetContactInformation(ContactInformationType.DisplayName).ToString();
contactResult.SipAddress = c.Uri;
searchForContactResults.Add(contactResult);
}
if (ResultOfSearchForContactEvent != null) ResultOfSearchForContactEvent(searchForContactResults); //returns results to subscriber fine, however I'd perfer not to do this
}
, _asyncState);
//I want to return List<MeetingContact> here once BeginSearch has completed
}
EDIT:
so I've essentially done it by making the thread sleep until BeginSearch is complete. There must be a better way?
public List<MeetingContact> SearchForContact(string search)
{
var searchFields = _LyncClient.ContactManager.GetSearchFields();
object[] _asyncState = { _LyncClient.ContactManager, search };
bool isComplete = false;
_LyncClient.ContactManager.BeginSearch(search, SearchProviders.GlobalAddressList | SearchProviders.ExchangeService
, searchFields
, SearchOptions.Default
, 10
, result =>
{
searchForContactResults = new List<MeetingContact>();
SearchResults results = null;
results = ((ContactManager)_asyncState[0]).EndSearch(result);
if(results == null)
return;
MeetingContact contactResult = new MeetingContact();
foreach (var searchResult in results.AllResults)
{
var c = searchResult.Result as Contact;
contactResult.FullName = c.GetContactInformation(ContactInformationType.DisplayName).ToString();
contactResult.SipAddress = c.Uri;
searchForContactResults.Add(contactResult);
}
isComplete = true;
}, _asyncState);
while (isComplete == false)
{
Thread.Sleep(50);
}
return searchForContactResults;
}