C#如何捕获异步结果?

时间:2016-09-20 16:27:38

标签: c# asynchronous lync-2013 lync-client-sdk

我是C#& amp;的新手我正在尝试使用Lync SDK以编程方式搜索Lync用户以获取其状态。我不确定如何在执行异步回调时将结果传递给webservice响应。

这是代码:

Webservice Controller GET端点:

        // GET: api/Lync/5
            public String Get(int id)
    {
        log.Info("[GET] Search for Lync User: " + id);

        Lync lync = new Lync();

        ////lync.signIn();
        Boolean isSignedIn = lync.isUserSignedIn();

        if (isSignedIn)
        {
            log.Info("User is Signed In");
            Console.Write("Enter search key : ");
            lync.Search("medina");

            //lync.Search("medina",
            //(lyncContacts) =>
            //{
            //    log.Debug("Search Results Callback fired!");
            //    log.Info("Results found: " + lyncContacts.Count);
            //    return lyncContacts.ToString();
            //});
            //Console.WriteLine(name);
            //Console.ReadLine();
            return "testUser";
        }
        else
        {
            log.Info("User is not Signed In!");
            // TODO: Return status 500
            return "testUser";
        }
        //Console.ReadLine();
        //return "testUser";
    }

上述方法调用业务服务lync.search(..),如下所示:

        public void Search(string searchKey)
    {
        List<LyncContact> contactList = new List<LyncContact>();
        //List<ContactInformationType> ContactInformationList = new List<ContactInformationType>();
        //ContactInformationList.Add(ContactInformationType.Activity);
        //ContactInformationList.Add(ContactInformationType.Availability);
        // ContactInformationList.Add(ContactInformationType.CapabilityString);

        //ContactSubscription contactSubscription = LyncClient.GetClient().ContactManager.CreateSubscription();

        Console.WriteLine("Searching for contacts on " + searchKey);

        LyncClient.GetClient().ContactManager.BeginSearch(
             searchKey,
             (ar) =>
             {
                 SearchResults searchResults = LyncClient.GetClient().ContactManager.EndSearch(ar);
                 if (searchResults.Contacts.Count > 0)
                 {
                     log.Info("Search results found: " + searchResults.Contacts.Count);

                     Console.WriteLine(searchResults.Contacts.Count.ToString() + " found");

                     foreach (Contact contact in searchResults.Contacts)
                     {
                         String displayName = contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
                         ContactAvailability currentAvailability = (ContactAvailability)contact.GetContactInformation(ContactInformationType.Availability);

                         Console.WriteLine(
                              contact.GetContactInformation(ContactInformationType.DisplayName).ToString() + "   " + contact.GetContactInformation(ContactInformationType.Availability).ToString());

                         log.Debug("Display Name: " + displayName);
                         log.Debug("Availability: " + currentAvailability);
                         LyncContact lyncContact = new LyncContact.Builder().DisplayName("Snehil").Availability("Busy").build();

                         contactList.Add(lyncContact);
                         //done(contactList);
                     }
                     return;
                 }
                 else
                 {
                     log.Info("No Results found!");
                     //done(contactList);
                     return;
                 }
             },
             null);
    }      else
                 {
                     log.Info("No Results found!");
                     //done(contactList);
                     return;
                 }
             },
             null);
    }

我尝试使用Task + await,但我很难弄清楚如何从搜索方法的结果中返回回调函数的结果。我如何在控制器类中捕获它?

2 个答案:

答案 0 :(得分:1)

如果您想使用async / await模式进行此项使用Task.FromAsync https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync(v=vs.110).aspx

谷歌的例子。像这样:

public async Task<List<LyncContact>> SearchAsync(string searchKey)
{
    List<LyncContact> contactList = new List<LyncContact>();

    Console.WriteLine("Searching for contacts on " + searchKey);

    var cm = LyncClient.GetClient().ContactManager;
    var searchResults = await Task<SearchResults>.Factory.FromAsync<String>(
        cm.BeginSearch,
        cm.EndSearch, searchKey, null);

    if (searchResults.Contacts.Count > 0)
    {

        Console.WriteLine(searchResults.Contacts.Count.ToString() + " found");

        foreach (Contact contact in searchResults.Contacts)
        {
            String displayName = contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
            ContactAvailability currentAvailability = (ContactAvailability)contact.GetContactInformation(ContactInformationType.Availability);

            Console.WriteLine(
                 contact.GetContactInformation(ContactInformationType.DisplayName).ToString() + "   " + contact.GetContactInformation(ContactInformationType.Availability).ToString());

            LyncContact lyncContact = new LyncContact.Builder().DisplayName("Snehil").Availability("Busy").build();

            contactList.Add(lyncContact);
        }
    }

    return contactList
}

在控制器中,您可以执行以下操作:

public async Task<String> Get(int id)
{
    log.Info("[GET] Search for Lync User: " + id);

    Lync lync = new Lync();

    ////lync.signIn();
    Boolean isSignedIn = lync.isUserSignedIn();

    if (isSignedIn)
    {
        log.Info("User is Signed In");
        Console.Write("Enter search key : ");
        var lyncContacts = await SearchAsync("medina");

        log.Info("Results found: " + lyncContacts.Count);
        return lyncContacts.ToString();
    }
    else
    {
        log.Info("User is not Signed In!");
        // TODO: Return status 500
        return "testUser";
    }
    //Console.ReadLine();
    //return "testUser";
}

或者您可以使用TaskCompletionSource,请参阅http://blog.stephencleary.com/2012/07/async-interop-with-iasyncresult.html(较旧的帖子,但原则仍有效。

警告

我无法编译,因为我无法访问您使用的库。它应该工作但可能存在一些编译错误

它做什么

回调并不是一个很好的模型,正如你已经发现的那样。使用Tasks和async / await模型更容易使用。幸运的是,对于你我来说,他们已经创建了几种方法,可以充当旧模型和新模型之间的桥梁。使用Task.FromAsync,您可以将IAsyncResult方法转换为更易于使用的基于任务的方法。 Stephen Cleary写了一些关于他们的好博客。请参阅我之前提到的帖子。

答案 1 :(得分:0)

通过查看已注释掉的代码,您似乎试图为Search函数提供某种回调。这样可行,它应该是Action<Microsoft.Lync.Model.SearchResults>

类型
public void Search(string searchKey, Action<SearchResults> callback)
{
   ....
   LyncClient.GetClient().ContactManager.BeginSearch(
             searchKey,
             (ar) =>
             {
                 SearchResults searchResults = LyncClient.GetClient().ContactManager.EndSearch(ar);
                 callback(searchResults);
             });
   ....
}

然后只需取消注释控制器中的代码:

lync.Search("medina",
        (lyncContacts) =>
        {
            log.Debug("Search Results Callback fired!");
            log.Info("Results found: " + lyncContacts.AllResults.Count);                
        });