Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active April 25, 2023 03:44
Show Gist options
  • Save relyky/cd59d6b274713fb57c4b60c21b3913c7 to your computer and use it in GitHub Desktop.
Save relyky/cd59d6b274713fb57c4b60c21b3913c7 to your computer and use it in GitHub Desktop.
Task, AsyncAction, CatchHandling, 把同步的 Action 叫用轉換成非同步的 Action 叫用。
/// ref→[Converting Action method call to async Action method call](https://stackoverflow.com/questions/33941583/converting-action-method-call-to-async-action-method-call)
/// 把同步的 Action 叫用轉換成非同步的 Action 叫用。
/// Action ==> async Action
Execute(()=> { do_some_thing });
轉換成:即 Action ==> 非同步化 ==> Task<Func>
ExecuteAsync(async ()=> { do_some_thing_async });
//=================================
//## 同步的 Action 叫用語法
void Execute(Action action)
{
try
{
action();
}
finally
{
}
}
===> 轉換成
//## 非同步的 Action 叫用語法
// 需把 Action 換成 Func<Task> 就可以 await 了
async Task ExecuteAsync(Func<Task> func)
{
try
{
await func();
}
finally
{
}
}
List<TodoDto> dataList = new();
bool f_testFail = false;
string newTodoDesc = string.Empty;
bool f_loading = false;
string errMsg = string.Empty;
//protected override async Task OnInitializedAsync()
//{
// await base.OnInitializedAsync();
// await HandleQuery();
//}
Task HandleQuery() => CatchHandling(async () =>
{
await Task.Delay(500);
var qryArgs = new TodoQryAgs
{
Msg = f_testFail ? "測試邏輯失敗" : "今天天氣真好",
Amt = 999
};
dataList = await bizApi.QryDataListAsync(qryArgs);
});
Task HandleAdd() => CatchHandling(async () =>
{
var newTodo = await bizApi.AddFormDataAsync(newTodoDesc);
// Success
dataList.Add(newTodo);
newTodoDesc = string.Empty;
});
//# AOP with Decorator
async Task CatchHandling(Func<Task> action)
{
try
{
f_loading = true;
errMsg = string.Empty;
await action();
}
catch (ApiException ex)
{
if (ex.StatusCode == HttpStatusCode.BadRequest)
{
var msg = await ex.GetContentAsAsync<ErrMsg>();
errMsg = $"ApiException: {msg.Severity}-{msg.Message}";
}
else
{
errMsg = $"ApiException: {ex.Message}";
}
}
catch (Exception ex)
{
errMsg = "EXCEPTION: " + ex.Message;
}
finally
{
f_loading = false;
}
}
// 在同步語法的宣告:
void CatchHandling(Action action) {}
// 轉換成非同步就變成如下:
// 即 Action ==> 非同步化 ==> Task<Func>
async Task CatchHandling(Func<Task> action)
{
try
{
f_loading = true;
errMsg = string.Empty;
// 執行
await action();
}
catch (ApiException ex)
{
if (ex.StatusCode == HttpStatusCode.BadRequest)
{
var msg = await ex.GetContentAsAsync<ErrMsg>();
errMsg = $"ApiException: {msg.Severity}-{msg.Message}";
}
else
{
errMsg = $"ApiException: {ex.Message}";
}
}
catch (Exception ex)
{
errMsg = "EXCEPTION: " + ex.Message;
}
finally
{
f_loading = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment