你能提供一个如何使用后台工作者的例子吗?我已经按照asp.net样板文档中提供的说明创建了后台工作人员。继承我的类
public class ContactValidationBackgroundWorker : BackgroundWorkerBase, ITransientDependency重写Start方法并放入非阻塞Task.Run(MyMethod)。然后我将等待指令添加到覆盖的方法WaitToStop中,添加类似myTask.Wait();
此方法开始,但它阻止执行主要进程的工作。我使用的是Asp.net(样板)核心+角度(SPA),我将其添加到应用服务层中。
发布于 2017-12-11 15:56:22
public partial class MainWindow : Window
{
//defining the backgroundworker
private BackgroundWorker bgworker = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
initializeBackgroundWorker();
}
private void initializeBackgroundWorker()
{
bgworker.DoWork += MyBackgroundWorker_DoWork;
}
private void MyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//method you want to execute in the backgroundWorker
MyMethod();
}
private void Mouse_Enter(object sender, MouseEventArgs e)
{
//call the backgroundWorker and execute it
//This will execute the method simultaneouly with other methods
//without blocking the UI
bgworker.RunWorkerAsync();
}
private void MyMethod()
{
//your method's code
}
}上面的代码展示了如何使用C#在WPF或winform应用程序中define, initialize and execute一个backgroundWorker。请参考代码中的内联注释,以了解代码的每个部分的作用。
发布于 2017-12-12 20:08:53
public class MakeInactiveUsersPassiveWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
{
private readonly IRepository<User, long> _userRepository;
public MakeInactiveUsersPassiveWorker(AbpTimer timer, IRepository<User, long> userRepository)
: base(timer)
{
_userRepository = userRepository;
Timer.Period = 5000; //5 seconds (good for tests, but normally will be more)
}
[UnitOfWork]
protected override void DoWork()
{
using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var oneMonthAgo = Clock.Now.Subtract(TimeSpan.FromDays(30));
var inactiveUsers = _userRepository.GetAllList(u =>
u.IsActive &&
((u.LastLoginTime < oneMonthAgo && u.LastLoginTime != null) || (u.CreationTime < oneMonthAgo && u.LastLoginTime == null))
);
foreach (var inactiveUser in inactiveUsers)
{
inactiveUser.IsActive = false;
Logger.Info(inactiveUser + " made passive since he/she did not login in last 30 days.");
}
CurrentUnitOfWork.SaveChanges();
}
}
}阅读=> https://aspnetboilerplate.com/Pages/Documents/Background-Jobs-And-Workers
https://stackoverflow.com/questions/47747926
复制相似问题