我有一个winform应用程序(一个表单),在这个表单上有一个RichTextBox.在这个表单的构造函数中,我创建了一个类的实例MyClass.在"Form_Load"中,我Initialisation从MyClass实例中调用该方法.
在表单构造函数中
myClass = new MyClass(RichTextBox richTextBox);
Run Code Online (Sandbox Code Playgroud)
在Form_Load中
myClass.Initialisation();
Run Code Online (Sandbox Code Playgroud)
在Initialisation方法中,在循环中,我读了一些参数做其他的东西.为了不冻结应用程序(因为某些操作可能需要一段时间,几秒钟),我使用了BackgroundWorker.我这样使用它(见下面的代码).
当我执行时,我收到此错误:跨线程操作无效:控制'richTextBox'从其创建的线程以外的线程访问.
你能告诉我怎么解决这个问题吗?当我不访问时,工作完美richTextBox
public Class MyClass
{
static BackgroundWorker _bw;
public MyClass()
{
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_bw.DoWork += bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
foreach (....)
{
if (....)
{
richtextBox.Text.AppendText("MyText");
}
}
e.Result = true;
}
static void bw_RunWorkerCompleted(object …Run Code Online (Sandbox Code Playgroud) 我正在编写一个进度条类,每个n刻度都会输出一个更新的进度条std::ostream:
class progress_bar
{
public:
progress_bar(uint64_t ticks)
: _total_ticks(ticks), ticks_occured(0),
_begin(std::chrono::steady_clock::now())
...
void tick()
{
// test to see if enough progress has elapsed
// to warrant updating the progress bar
// that way we aren't wasting resources printing
// something that hasn't changed
if (/* should we update */)
{
...
}
}
private:
std::uint64_t _total_ticks;
std::uint64_t _ticks_occurred;
std::chrono::steady_clock::time_point _begin;
...
}
Run Code Online (Sandbox Code Playgroud)
我还想输出剩余的时间.我在另一个问题上找到了一个公式,说明剩余的时间是(变量名称已更改为适合我的班级):
time_left = (time_taken / _total_ticks) * (_total_ticks - _ticks_occured)
我想填补了我的课的部分是 …