English 中文(简体)
用!
原标题:Use !Task.IsCompleted to show user current progress in GUI

我的任务可能要完成。

我尝试了简单的解说,但出于某种原因,它打开了全球倡议的read子。 我认为,这项任务是同步的,在任务执行期间,全球倡议会更新。

这项任务是否可行?

    private void button5_Click(object sender, EventArgs e)
    {
        var task = Task.Factory.StartNew(() => DoSomething());
        while (!task.IsCompleted)
        {
            label1.Text += ".";
            if (label1.Text.Length == 5)
                label1.Text = ".";
        }
    }

    private void DoSomething()
    {
        Thread.Sleep(5000);
    }

<><>UPDATE: 在达米恩的答复之后,我尝试了以下几个方面,但万国邮联已接手。

        private void button5_Click(object sender, EventArgs e)
        {
            var task = Task.Factory.StartNew(() => DoSomething());
        }
        public delegate void dgUpdateLabel();

        private void UpdateLabel()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new dgUpdateLabel(UpdateLabel), new object[] { });
            }
            else
            {
                label1.Text += ".";
                if (label1.Text.Length == 5)
                    label1.Text = ".";
            }
        }

        private void DoSomething()
        {
            var task = Task.Factory.StartNew(() => Sleep());
            while (!task.IsCompleted)
            {
                UpdateLabel();
            }
        }

        private void Sleep()
        {
            Thread.Sleep(5000);
        }

<>>><>>>> 我认为,试图更新标签的速度太快,无法处理。 如果在经过更新的实验室方法之后,你将“Thread.Sleep(500)”称作它按预期运作。

最佳回答

:

private void Form1_Load(object sender, EventArgs e)
{
  CancellationTokenSource cts = new CancellationTokenSource();
  Task worker = new Task(() => DoSomething());
  Task ui_updater = new Task(() => UpdateGui(CancellationToken token));
  worker.Start();
  updater.Start();
  // Worker task completed, cancel GUI updater.
  worker.ContinueWith(task => cts.Cancel());
}
private void DoSomething()
{
 // Do an awful lot of work here.
}
private void UpdateGui(CancellationToken token)
{ 
  while (!token.IsCancellationRequested)
 {      
   UpdateLabel();
   Thread.Sleep(500);
 }
}
private void UpdateLabel()
{
  if (this.InvokeRequired)
  {
   this.BeginInvoke(new Action(() => UpdateLabel()), new object[] { });
  }
    else
    {
        label1.Text += ".";
        if (label1.Text.Length >= 5)
            label1.Text = ".";
    }
}
问题回答

贵方需要从<代码>button_Click的手稿中回来,然后才能更新。 也许会看花一个时间,以便定期进行更新。

此时,您的问答机正在坐着紧凑的<条码>,同时(!task.IsCompleted),并可能利用你所有的记名牌照。


To use a timer, you d have to expose your task variable at a higher level (e.g. as a private field) rather than a local variable.

I ve adjusted Alex s code, which IMO had multiple errors (and was not runnable):

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForm
{
  public partial class Form1 : Form
  {
    readonly CancellationTokenSource _cts = new CancellationTokenSource();
    public Form1()
    {
      InitializeComponent();
    }
    private void button5_Click(object sender, EventArgs e)
    {
      var task = Task.Factory.StartNew(() => DoSomething());
      Task updatingLabel = Task.Factory.StartNew(() => UpdateLabelValidated(_cts));
      task.ContinueWith(_=> _cts.Cancel());
    }
    private void DoSomething()
    {
      Thread.Sleep(20000);
    }
    private void UpdateLabelValidated(CancellationTokenSource token)
    {
      while (!token.IsCancellationRequested)
      {
        UpdateLabel();
        Thread.Sleep(500);
      }
    }
    private void UpdateLabel()
    {
      if (this.InvokeRequired)
      {
        this.BeginInvoke(new Action(UpdateLabel), new object[] { });
      }
      else
      {
        label1.Text += ".";
        if (label1.Text.Length > 5)
          label1.Text = ".";
      }
    }
  }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签