简体   繁体   English

异步任务并在C#中等待

[英]Async Task and await in C#

I'm working on Async webservice call and was playing with this Task and await construction: 我正在处理异步Web服务调用,并且正在玩此Task并等待构建:

private static async Task<RSAParameters> GetPublicSecretKey(ICoreIdentityService identityChannel)
{
        Object state = null;
        var t = Task<RSAParameters>.Factory.FromAsync(
            identityChannel.BeginGetPublicKey,
            identityChannel.EndGetPublicKey,
                null, state, TaskCreationOptions.None);
        return await t;
}

//Methods definition:
//IAsyncResult BeginGetPublicKey(AsyncCallback callback, object asyncState)
//RSAParameters EndGetPublicKey(IAsyncResult result)

Building the code I get The type arguments for method .... cannot be inferred from usage. 构建我得到的代码无法从用法中推断方法..的类型参数。 Am I missing something? 我想念什么吗?

Thank's in advance. 提前致谢。 Cheers, inoel 欢呼声

任务和等待错误

Modified compiled code: 修改后的编译代码:

var t = Task<RSAParameters>.Factory.FromAsync(
    identityChannel.BeginGetPublicKey,
    identityChannel.EndGetPublicKey,
    TaskCreationOptions.None);

It appears that you are calling the FromAsync() method with your parameters in an unexpected order. 似乎您正在以意外顺序使用参数调用FromAsync()方法。

The error message itself suggests explicitly naming your parameters, so your code would look something along the lines of this: 错误消息本身建议显式命名参数,因此您的代码应类似于以下内容:

var t = Task<RSAParameters>.Factory.FromAsync(
                asyncResult: identityChannel.BegineGetPublicKey,
                endMethod: identityChannel.EndGetPublicKey,
                creationOptions: TaskCreationOptions.None,
                scheduler: state);

Alternatively, you could correct the order of your parameters, and this should solve the problem. 或者,您可以更正参数的顺序,这应该可以解决问题。 The closest overload I can find is this: 我能找到的最接近的重载是这样的:

public Task<TResult> FromAsync<TArg1, TArg2>(Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions);

So assuming you intend to use this one, your code will need to be modified slightly to pass in the types of arg1, and arg2, then pass in an additional parameter: 因此,假设您打算使用此代码,则需要对代码进行一些修改以传入arg1和arg2的类型,然后传入一个附加参数:

Object state = null;
var t = Task<RSAParameters>.Factory.FromAsync<TArg1, TArg2>(
            beginMethod: identityChannel.BeginGetPublicKey,
            endMethod: identityChannel.EndGetPublicKey,
            arg1: null, // Either arg1, or arg2 is missing
            arg2: null, // from your code
            state: state,
            creationOptions: TaskCreationOptions.None);

return t;

I've left the named parameters here for clarity, but you should be able to remove these if you prefer. 为了清楚起见,我在这里保留了命名参数,但是如果愿意,您应该可以删除这些参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM