如何使用Task.factory.fromAsync与void方法

3

我正在使用WCF来执行插入数据的任务。我正在使用WCF的一个void函数来插入用户数据。

AceVqbzServiceClient aceVqbzClientService = new AceVqbzServiceClient();
aceVqbzClientService.OpenAsync();
IAceVqbzService aceVqbzTypeService = aceVqbzClientService as IAceVqbzService;

Task.Factory.FromAsync(
            aceVqbzTypeService.BeginSaveUserOrganizationLinking,
            aceVqbzTypeService.EndSaveUserOrganizationLinking,
            objUser_OrganizationDetail, 
            TaskCreationOptions.None);

aceVqbzClientService.CloseAsync();

这是函数:

使用时没有出现任何问题,但是数据并没有通过此函数插入。 请给我解决方案,这样我就可以实现它。


比如什么? - Yuval Itzchakov
2个回答

2

您需要使用await异步等待从FromAsync返回的Task

public async Task FooAsync()
{
    AceVqbzServiceClient aceVqbzClientService = new AceVqbzServiceClient();
    await aceVqbzClientService.OpenAsync();
    IAceVqbzService aceVqbzTypeService = aceVqbzClientService as IAceVqbzService;

    await Task.Factory.FromAsync(
                       aceVqbzTypeService.BeginSaveUserOrganizationLinking,
                       aceVqbzTypeService.EndSaveUserOrganizationLinking,
                       objUser_OrganizationDetail, TaskCreationOptions.None);

    await aceVqbzClientService.CloseAsync();
}

你不觉得你也应该“等待”其他异步调用吗? - H H
谢谢您提供答案,但它在我的代码中无法运行。 - Mukesh Kumar

-1

这是我的问题的答案

 try
        {
            AceVqbzServiceClient aceVqbzClientService = new AceVqbzServiceClient();
            aceVqbzClientService.OpenAsync();
            IAceVqbzService aceVqbzTypeService = aceVqbzClientService as IAceVqbzService;

            var asyncResult = aceVqbzTypeService.BeginSaveUserOrganizationLinking( objUser_OrganizationDetail, null, null );
            asyncResult.AsyncWaitHandle.WaitOne();


        }
        catch ( Exception ex )
        {
            throw;
        }

这行代码运行正常


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接