简体   繁体   English

如何在线程中设置组件属性而不在C#.NET中引发错误?

[英]How do you set a component property from within a thread without throwing an error in C# .NET?

I have a user interface which needs to be updated by a function running in a backgroundworker (a different thread from the primary one). 我有一个用户界面,需要通过在backgroundworker工作程序中运行的函数(与主要工作程序不同的线程)进行更新。

I would like to effectively be able to do the following without throwing an exception: 我希望能够在不抛出异常的情况下有效地执行以下操作:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        MyProgresssbar.value = val;
        MyLabel.text = "Still going...";
    }

For example, could a delegate function be written that sets a component property (I don't want to have a function for each property change). 例如,可以编写一个委托函数来设置一个组件属性(我不希望每个属性更改都有一个函数)。

Thanks in advance. 提前致谢。

You should use BackgroundWorker's built-in progress reporting functionality. 您应该使用BackgroundWorker的内置进度报告功能。

As a more general answer, you can run code in the UI thread (aynchronously) by calling 作为更一般的答案,您可以通过调用在UI线程中运行代码(异步)

someControl.BeginInvoke(new Action(delegate { ... }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# .NET 中,当您知道对象的另一个属性时,如何访问该对象的另一个属性? - In C# .NET, how do you access a property of an object when you know another property of an object? C#:如何从另一个线程访问主UI线程中的整数? - C#: How do you access an integer in the main UI thread from another thread? 如何在用 c# 编写的 UWP 应用程序中从 Windows 运行时组件 (c#) 调用函数? - How do you call functions from a Windows Runtime Component (c#) in a UWP app written in c#? C#.net应用程序中的分叉线程死掉并且没有引发任何错误 - Forked thread in C# .net App dies inexplicably and without throwing any errors C#Winforms:如何将焦点设置为窗体上的DataGridView组件? - C# Winforms: how do you set focus to a DataGridView component on a form? 如何在ac#AWS lambda函数中设置环境变量? - How do you set an environment variable within a c# AWS lambda function? 如何从C#中的工作线程关闭ZMQ QueueDevice - How do you shutdown a ZMQ QueueDevice from a worker thread in c# c#如何对递归目录搜索进行线程化? - c# How do you thread a recursive directory search? 在站点中使用C#查询外部IP时,如何处理抛出超时错误的现有代码? - How do you handle existing code throwing a timeout error when querying a site for your external IP in C#? 从线程内更新datagridview会导致错误C#Winform - updating datagridview from within a thread causes error c# winform
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM