我最近将我的项目升级到ASP.NET 4.5,我等了很长时间才使用4.5的异步功能.阅读文档后,我不确定是否可以改进我的代码.
我想异步执行一个任务然后忘记它.我目前正在这样做的方式是创建委托然后使用BeginInvoke.
这是我项目中的一个过滤器,每次用户访问必须审计的资源时,都会在我们的数据库中创建一个审计:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var id = WebSecurity.CurrentUserId;
var invoker = new MethodInvoker(delegate
{
var audit = new Audit
{
Id = Guid.NewGuid(),
IPAddress = request.UserHostAddress,
UserId = id,
Resource = request.RawUrl,
Timestamp = DateTime.UtcNow
};
var database = (new NinjectBinder()).Kernel.Get<IDatabaseWorker>();
database.Audits.InsertOrUpdate(audit);
database.Save();
});
invoker.BeginInvoke(StopAsynchronousMethod, invoker);
base.OnActionExecuting(filterContext);
}
Run Code Online (Sandbox Code Playgroud)
但是为了完成这个异步任务,我需要始终定义一个回调,如下所示:
public void StopAsynchronousMethod(IAsyncResult result)
{
var state = (MethodInvoker)result.AsyncState;
try
{
state.EndInvoke(result);
}
catch (Exception e)
{
var username …Run Code Online (Sandbox Code Playgroud) 我有一个文件夹,用于保存我所有的 Git 存储库。我通常只是git pull为了得到我的更改,但是现在我有超过 50 个存储库,必须为每个文件夹执行此操作成为一种负担。
如何运行一个命令来遍历每个 repo 并为我更新它?
我有一个禁用延迟加载的数据库上下文.我正在使用急切加载来加载我的所有实体.我无法更新多对多的关系.
这是存储库.
public class GenericRepository<TEntity> : IGenericRepository<TEntity>
where TEntity : class
{
... other code here...
public virtual void Update(TEntity t)
{
Set.Attach(t);
Context.Entry(t).State = EntityState.Modified;
}
...other code here...
}
Run Code Online (Sandbox Code Playgroud)
这是用户模型.
public partial class User
{
public User()
{
this.Locks = new HashSet<Lock>();
this.BusinessModels = new HashSet<BusinessModel>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string JobTitle …Run Code Online (Sandbox Code Playgroud) 我正在尝试将变量设置为值,但值可能是nil.如果是的话,我需要做一些处理.这是一些示例代码:
car = cached_car || do
new_car = Car.new
# do stuff to the object here
send_car_to_cache(new_car)
new_car
end
Run Code Online (Sandbox Code Playgroud)
不幸的是,它告诉我有一个意外的do阻止.我在这做错了什么?
编辑:上下文可能令人困惑,所以这是我正在使用它的真实场景.
def tableView(table_view, cellForRowAtIndexPath:index_path)
cell = table_view.dequeueReusableCellWithIdentifier(CELL_ID) || begin
PostTableViewCell.alloc.initWithStyle(
UITableViewCellStyleDefault, reuseIdentifier: CELL_ID
)
end
configure_cell(cell, index_path)
cell
end
Run Code Online (Sandbox Code Playgroud)