gpt4 book ai didi

c# - 在 C# 中从线程更新进度条

转载 作者:太空狗 更新时间:2023-10-30 00:11:22 27 4
gpt4 key购买 nike

    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 的情况下从消费者更新进度条呢?

请注意,我使用了 progressbar.Invokedelegate 但没有用。

最佳答案

你需要两件事。第一个显然是一个线程,另一个是调用者。

Invokers 将允许您从线程内部更改窗口的控件。这是示例:

Invoke((MethodInvoker)delegate
{
Label1.text = "asd";
}

线程是这样运行的:

some_thread = new Thread
(delegate()
{

{
//some_thread code
}
});
some_thread.Start();

您还需要在文件开头添加using System.Threading;

所以,最终的代码应该是这样的:

some_thread = new Thread
(delegate()
{

{
for(;;)
{
Invoke((MethodInvoker)delegate
{
//update the progress bar here
}
}
}
});
some_thread.Start();

关于c# - 在 C# 中从线程更新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13141280/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com