C# .NET WebApi异步控制器操作将永远执行
我很难理解.NET Async/Await示例,例如官方教程 根据我收集的信息,要使控制器动作异步,我必须:C# .NET WebApi异步控制器操作将永远执行,c#,asp.net,asynchronous,asp.net-web-api,C#,Asp.net,Asynchronous,Asp.net Web Api,我很难理解.NET Async/Await示例,例如官方教程 根据我收集的信息,要使控制器动作异步,我必须: 在方法名称之前添加async 在主任务运行之前添加wait 如果我从存储或存储库中提取,那么我必须将Task.Run()添加到存储方法中 async方法必须返回Task 当我这样做时,编译器中没有错误或警告,该方法只是挂起。我哪里做错了 PostsController.cs public async Task<IHttpActionResult> Get()
async
wait
Task.Run()
添加到存储方法中async
方法必须返回Task
public async Task<IHttpActionResult> Get()
{
PostsStore store = new PostsStore();
List<Post> AsyncResult = await store.GetPosts();
return Ok(AsyncResult);
}
public async Task<List<Post>> GetPosts()
{
List<Post> result = await Task.Run(() => {
List<Post> posts = new List<Post>();
string conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "GetPosts";
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Post post = new Post()
{
PostId = (int)(dr["PostId"]),
Title = dr.SafeGetString("Title"),
Body = dr.SafeGetString("Body"),
SaveTitle = dr.SafeGetString("SaveTitle"),
SaveBody = dr.SafeGetString("SaveBody"),
Slug = dr.SafeGetString("Slug"),
State = dr.SafeGetString("State"),
IsPublished = (bool)(dr["IsPublished"]),
LastSaved = (DateTime)(dr["LastSaved"]),
CreateDate = (DateTime)(dr["CreateDate"])
};
posts.Add(post);
}
dr.Close();
connection.Close();
return posts;
}
});
return result;
}
公共异步任务Get()
{
PostsStore=新的PostsStore();
List AsyncResult=wait store.GetPosts();
返回Ok(异步结果);
}
PostsStore.cs
public async Task<IHttpActionResult> Get()
{
PostsStore store = new PostsStore();
List<Post> AsyncResult = await store.GetPosts();
return Ok(AsyncResult);
}
public async Task<List<Post>> GetPosts()
{
List<Post> result = await Task.Run(() => {
List<Post> posts = new List<Post>();
string conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "GetPosts";
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Post post = new Post()
{
PostId = (int)(dr["PostId"]),
Title = dr.SafeGetString("Title"),
Body = dr.SafeGetString("Body"),
SaveTitle = dr.SafeGetString("SaveTitle"),
SaveBody = dr.SafeGetString("SaveBody"),
Slug = dr.SafeGetString("Slug"),
State = dr.SafeGetString("State"),
IsPublished = (bool)(dr["IsPublished"]),
LastSaved = (DateTime)(dr["LastSaved"]),
CreateDate = (DateTime)(dr["CreateDate"])
};
posts.Add(post);
}
dr.Close();
connection.Close();
return posts;
}
});
return result;
}
public异步任务GetPosts()
{
列表结果=等待任务。运行(()=>{
列表帖子=新列表();
字符串conn=ConfigurationManager.ConnectionString[“DefaultConnection”].ConnectionString;
使用(SqlConnection=newsqlconnection(conn))
{
SqlCommand=newsqlcommand();
command.Connection=连接;
command.CommandText=“GetPosts”;
command.CommandType=System.Data.CommandType.StoredProcess;
connection.Open();
SqlDataReader dr=command.ExecuteReader();
while(dr.Read())
{
Post Post=新职位()
{
PostId=(int)(dr[“PostId”]),
Title=dr.SafeGetString(“Title”),
Body=dr.SafeGetString(“Body”),
SaveTitle=dr.SafeGetString(“SaveTitle”),
SaveBody=dr.SafeGetString(“SaveBody”),
Slug=dr.SafeGetString(“Slug”),
State=dr.SafeGetString(“State”),
IsPublished=(bool)(dr[“IsPublished”]),
LastSaved=(日期时间)(dr[“LastSaved”]),
CreateDate=(日期时间)(dr[“CreateDate”])
};
增加(员额);
}
Close博士();
connection.Close();
返回岗位;
}
});
返回结果;
}
无需执行任务。在此处运行。您可以考虑重构该方法以利用可用的异步调用。< /P>
public class PostsStore {
public async Task<List<Post>> GetPostsAsync() {
var posts = new List<Post>();
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var connection = new SqlConnection(connectionString)) {
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "GetPosts";
command.CommandType = System.Data.CommandType.StoredProcedure;
await connection.OpenAsync();
using (var reader = await command.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) {
var post = new Post() {
PostId = (int)(reader["PostId"]),
Title = reader.SafeGetString("Title"),
Body = reader.SafeGetString("Body"),
SaveTitle = reader.SafeGetString("SaveTitle"),
SaveBody = reader.SafeGetString("SaveBody"),
Slug = reader.SafeGetString("Slug"),
State = reader.SafeGetString("State"),
IsPublished = (bool)(reader["IsPublished"]),
LastSaved = (DateTime)(reader["LastSaved"]),
CreateDate = (DateTime)(reader["CreateDate"])
};
posts.Add(post);
}
}
}
return posts;
}
}
公共类邮局{
公共异步任务GetPostsAsync(){
var posts=新列表();
var connectionString=ConfigurationManager.connectionString[“DefaultConnection”]。connectionString;
使用(var连接=新的SqlConnection(connectionString)){
var命令=新的SqlCommand();
command.Connection=连接;
command.CommandText=“GetPosts”;
command.CommandType=System.Data.CommandType.StoredProcess;
等待连接。OpenAsync();
使用(var reader=await command.ExecuteReaderAsync()){
while(等待reader.ReadAsync()){
var post=new post(){
PostId=(int)(读卡器[“PostId”]),
Title=reader.SafeGetString(“Title”),
Body=reader.SafeGetString(“Body”),
SaveTitle=reader.SafeGetString(“SaveTitle”),
SaveBody=reader.SafeGetString(“SaveBody”),
Slug=reader.SafeGetString(“Slug”),
State=reader.SafeGetString(“State”),
IsPublished=(bool)(读卡器[“IsPublished”]),
LastSaved=(DateTime)(读卡器[“LastSaved”]),
CreateDate=(DateTime)(读卡器[“CreateDate”])
};
增加(员额);
}
}
}
返回岗位;
}
}
注意更新方法名以反映异步方法的命名约定
public async Task<IHttpActionResult> Get() {
var store = new PostsStore();
var posts = await store.GetPostsAsync();
return Ok(posts);
}
公共异步任务Get(){
var store=new PostsStore();
var posts=wait store.GetPostsAsync();
返回Ok(posts);
}
现在,考虑到这一点,考虑对上面的课程进行回顾/重构,这将有助于在将来继续保持它的问题。
不需要任务。运行。当它们被包装在使用语句中时,无需关闭它们。谢谢!我试试看。在高层次上,您还会重构什么?读者如何为帖子赋值?