c#如何捕获异步结果

本文关键字:结果 异步 何捕获 | 更新日期: 2023-09-27 18:07:51

我是c#新手&我试图使用Lync SDK以编程方式搜索Lync用户以获取其状态。我不确定如何将结果传递给web服务响应时,异步回调得到执行。

这是代码:

Webservice Controller GET endpoint:

        // 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);
    }

我试图使用任务+等待,但我很难弄清楚如何从回调函数返回结果作为搜索方法的结果。我如何在控制器类中捕获这个?

c#如何捕获异步结果

如果您想使用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模型要容易得多。对你和我来说幸运的是,他们已经创造了几种方法,可以作为新旧模型之间的桥梁。使用任务。从同步中,你可以将IAsyncResult方法转换为更容易使用的基于任务的方法。Stephen Cleary写了一些关于他们的不错的博客。看看我之前提到的帖子。

看起来,通过查看您的注释代码,您试图为您的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);                
        });