等待动作异常

时间:2018-08-04 15:48:43

标签: c# async-await

我有这个功能:

datetime.date

,它的调用者是:

public static async Task<T> Relay<T>(string uriController, T jsonObject)
{
    var json = string.Empty;
    try
    {
        LogHelpers.LogVerbose( "Enter " + uriController );
        using ( var client = new HttpClient() )
        {
            HttpResponseMessage response;
            client.BaseAddress = Uri;
            client.Timeout = new TimeSpan( 0, 0, 0, 20, 0 );
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue( "application/json" ) );
            if ( jsonObject != null )
            {
                var jsonInput = JsonConvert.SerializeObject( jsonObject );
                var contentPost = new StringContent( jsonInput, Encoding.UTF8, "application/json" );
                response = await client.PostAsync( uriController, contentPost ).ConfigureAwait( false );
            }
            else
            {
                response = await client.PostAsync( uriController, null ).ConfigureAwait( false );
            }

            response.EnsureSuccessStatusCode();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                return default(T);
            }
            json = await response.Content.ReadAsStringAsync().ConfigureAwait( false );
            LogHelpers.LogVerbose( "Exit " + uriController );
            SendNotification?.Invoke();
        }
    }
    catch (Exception e)
    {
        throw e;
    }

    return JsonConvert.DeserializeObject<T>(json);
}

从此运行:

private async void GetPiSystemInfo()
{
    SystemPiInfo = await RaspberryPi.Relay<SystemPiInfo>("Api/SystemPiInfo/IsConnected", null);
}

最终从中被召唤出来

private async Task<bool> RunTheMethod(Action myMethodName)
{
    await Task.Run(
        () =>
        {
            while (true)
            {
                try
                {
                    myMethodName();
                    return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        });
    return false;
}

这种体系结构的原因是,当我的应用程序启动时,它将连接到我的Raspberry Pi盒子。进行了几次api调用,以从该框中获取数据。

如果由于任何原因未建立连接或返回错误,我希望重新运行该操作,直到这样做为止(显然会中断)。

 Action[] Actions = new Action[10];

 Actions[0] = GetPiSystemInfo;
 await RunTheMethod(Actions[0]);

方法是通用的,因为它将在许多不同的地方调用。因此,每当发生服务器错误时,我都会捕获并丢弃堆栈。

发生的事情是

Task<T> Relay<T>()
调用该操作后就会立即调用

0 个答案:

没有答案