winform编程,在子线程中操作界面元素,之前有一种比较复杂 的写法,用了delegate。昨天在《C#本质论》中看到了一种比较简洁的写法,分享如下:
//有个label,名称是lblWeather,子线程中获取了天气信息,要显示在这个label上
private void updateWeatherInfo()
{
if (lblWeather.InvokeRequired)
{
MethodInvoker ivk = updateWeatherInfo;
lblWeather.BeginInvoke(ivk);
}
else
{
lblWeather.Text = weatherInfo; //本类的全局变量
}
}
缺点是不方便直接传参数,要用全局变量中转一下。