天天看點

ASP.NET 使用線程異步執行代碼塊

第一種:Thread

new Thread(() =>
{
  //執行代碼塊
}).Start();      
// GET: api/BackgroundWorker
[HttpGet]
[Route("start")]
public void StartWorker()
{
  
  //寫法1:
  //Thread thread = new Thread(this.DoBackGroundWork);
  
  //寫法2:
  Thread thread = new Thread(() => DoBackGroundWork());
  thread.Start();
  
  //寫法3:
  new Thread(() =>
  {
    //執行代碼塊
    //...
  }).Start();

}

public void DoBackGroundWork()
{
  //執行代碼塊
  //...
}      

第二種:BackgroundWorker

BackgroundWorker barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
{
  //執行代碼塊
};
barInvoker.RunWorkerAsync();      

參考文檔