我正在尝试使用线程并防止程序在线程繁忙时冻结.它应该显示进度(写入0/1)并且不仅仅是在完成后显示结果,同时冻结表格.
在当前程序中,我正在尝试写入文本框,实际上看到不断进展,并且表单不会受到其他线程任务的影响.
我现在拥有的是我可以使用调用写入带有线程的文本框,但它只显示结果(表单在线程繁忙时冻结),并且表单冻结.
表格图片:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiThreading
{
public partial class MultiThreading : Form
{
public MultiThreading()
{
InitializeComponent();
}
Thread writeOne, writeTwo;
private void writeText(TextBox textBox, string text)
{
if (textBox.InvokeRequired)
{
textBox.BeginInvoke((MethodInvoker)delegate()
{
for (int i = 0; i < 500; i++)
{
textBox.Text += text;
}
});
}
else
{
for (int i = 0; i < 500; i++)
{ …
Run Code Online (Sandbox Code Playgroud) 可能重复:
什么是C#使用块,为什么要使用它?
所以我刚刚注意到在msdn示例和一些stackoverflow问题上有回答,其中using语句在streamwriter等之前使用,但实际上有什么好处呢?因为我从未被教过/告知/读过任何使用它的理由.
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
Console.WriteLine(sr.ReadLine());
}
Run Code Online (Sandbox Code Playgroud)
代替:
StreamReader sr = new StreamReader(path);
while (sr.Peek() >= 0)
Console.WriteLine(sr.ReadLine());
Run Code Online (Sandbox Code Playgroud)