从主题更新进度条在C# [英] Updating Progress Bar from Thread in C#
问题描述
public class Consumer
{
Queue<int> queue;
Object lockObject;
public Consumer(Queue<int> queue, Object lockObject)
{
this.queue = queue;
this.lockObject = lockObject;
}
public void consume(string filepath)
{
int item = 0;
while (true)
{
lock (lockObject)
{
if (queue.Count == 0)
{
Monitor.PulseAll(lockObject);
continue;
}
item = queue.Dequeue();
if (item == 0)
{
break;
}
//do some staff
}
}
}
}
public class Producer
{
Queue<int> queue;
Object lockObject;
public int ProgressPercent = 0;
int TotalProducedElements = 0;
public bool check1 = false;
public Producer(Queue<int> queue, Object lockObject)
{
this.queue = queue;
this.lockObject = lockObject;
}
private bool IsPrime(int num)
{
if (num == 0)
return true;
num = Math.Abs(num);
for (int i = 2; i <= Math.Sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
public void produce(int target)
{
try
{
int seq = 0;
while (seq++ < target)
{
lock (lockObject)
{
int item = seq;
if (IsPrime(item))
{
queue.Enqueue(item);
}
TotalProducedElements++;
ProgressPercent = seq;
if (queue.Count == 0)
{
Monitor.PulseAll(lockObject);
}
}
}
queue.Enqueue(0);
}
catch (Exception e)
{
}
}
}
}
private void Start_Click(object sender, EventArgs e)
{
Object lockObj = new object();
Queue<int> queue = new Queue<int>();
Producer p = new Producer(queue, lockObj);
Consumer c = new Consumer(queue, lockObj);
int target = int.Parse(TargetText.Text);
string path = Path.Text;
Thread Thread1 = new Thread(() => p.produce(target));
Thread Thread2 = new Thread(()=>c.consume(path));
Thread1.Start();
Thread2.Start();
progressBar1.Maximum = target;
while(true)
{
if(p.ProgressPercent==0)
{
Thread.sleep(1000);
}
else
{
progressBar1.Value=p.ProgressPercent;
}
}
}
我有两个班在同一个队列工作。一体,以生产一组整数和
秒是消耗,从队列的整数。
,并在这一切我想更新由我的百分比进度条。
那么如何在不阻断我的GUI更新从消费进度条?
I have two classes working on same queue. one to produce a set of integers and the second is to consume that integers from queue. and during all this i want to update my progress bar by that percentage. So how to update progress bar from consumer without blocking for my GUI?
请注意我用progressbar.Invoke和deletegate,但没有奏效。
Note I have used progressbar.Invoke and deletegate but didn't work.
推荐答案
您需要两样东西。首先显然是一个线程,另一个是调用。
You need two things. First is obviously a thread, the other is invoker.
关注它或将让你从一个线程内改变窗口的控制。这里的例子:
Invokers will let you change window's controls from inside of a thread. Here's the example:
Invoke((MethodInvoker)delegate
{
Label1.text = "asd";
}
线程是跑是这样的:
some_thread = new Thread
(delegate()
{
{
//some_thread code
}
});
some_thread.Start();
您还需要添加使用的System.Threading;在文件的开头
所以,最终的代码应该是这样的:
So, the final code should look like this:
some_thread = new Thread
(delegate()
{
{
for(;;)
{
Invoke((MethodInvoker)delegate
{
//update the progress bar here
}
}
}
});
some_thread.Start();
这篇关于从主题更新进度条在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!