Task.Run如何传参和返回值
普通情况下Task.run是不能传参数的,只能返回值,但借助于匿名函数可以实现传参
主要核心理念就是借用了匿名函数变量域通用的原理,然后把主函数中的变量通过匿名函数传递过去
C#示例
Task启动带参数
Task启动带参数和返回值的方法
VB示例
Private Async Function receiveGaugeDataHandlerAsync(ByVal e As GaugeValueReceivedEventArgs) As Tasks.Task(Of SuccessFailResult)
Return Await Task.Run(Of SuccessFailResult)(Function() As SuccessFailResult
Return receiveGaugeDataHandlerTask(e)
End Function)
End Function
Private Function receiveGaugeDataHandlerTask(ByVal e As GaugeValueReceivedEventArgs) As SuccessFailResult
Return pRunResult
End Function
c#示例:
public static async Task<SuccessFailResult<List<ETYHVod>>> getVodByNameLikeAsync(string pConnectionString, string pNameSub) {
return await Task.Run<SuccessFailResult<List<ETYHVod>>>(() => { return getVodByNameLike(pConnectionString, pNameSub); });
}
public static SuccessFailResult<List<ETYHVod>> getVodByNameLike(string pConnectionString, string pNameSub) {
using (DAYHVod pDA = new DAYHVod(pConnectionString)) {
pDA.mCondition.name = $"%{pNameSub}%";
var pList = pDA.mFunctions.getListByCondition("searchByName");
return SuccessFailResult<List<ETYHVod>>.createSuccess(pList);
}
}