如何在窗口c#中启动和停止后台任务? [英] How to start and stop background task in window c#?

查看:75
本文介绍了如何在窗口c#中启动和停止后台任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个需要很长时间才能完成的应用程序,因为客户端服务器类型应用程序,我想同时开始另一个新任务。



我尝试了什么:



private async void button2_Click(object sender,EventArgs e)

{

await Task.Run(()=>

{

Thread.Sleep(1000);

});

MessageBox.Show(嗨来自UI线程!);

}

I have created one application which required long time to complete because client server type application and i want to start new another task at same time.

What I have tried:

private async void button2_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
Thread.Sleep(1000);
});
MessageBox.Show("Hi from the UI thread!");
}

推荐答案

线程是好的完成任务的选项。你可以同时运行2个线程,

见下面的代码片段

Thread is the good option to accomplish your task. You can run 2 threads simultaneously,
see below snippet
static void Main(string[] args)
  {
      ThreadStart threadStart1 = new ThreadStart(DoSomething);
      ThreadStart threadStart2 = new ThreadStart(DoSomething);
      Thread th1 = new Thread(threadStart1);
      Thread th2 = new Thread(threadStart2);

      th1.Start();
      th2.Start();

      th1.Join();
      th2.Join();

      Console.ReadLine();
  }

private static void DoSomething()
  {
      while (DateTime.Now < startTime)
      {
          //do nothing
      }

      //both threads will execute code here concurrently
  }


这篇关于如何在窗口c#中启动和停止后台任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆