开发者

Delegating code to run from main thread for handling gui from main thread

开发者 https://www.devze.com 2022-12-26 15:12 出处:网络
I have some code which is been running by a backgroundworker I\'d like some specific code which shows some GUI to run in the main thread context (2 reasons 1. it should be blocking 2.I know it\'s prob

I have some code which is been running by a backgroundworker I'd like some specific code which shows some GUI to run in the main thread context (2 reasons 1. it should be blocking 2.I know it's problematic to handle gui controls from a background worker) I raise an event pass the class and listen to the event in the mainForm from there I check if invoke required and reinvoke. then call the public method of the instance I want to run in the main thread. I have a few questions:

  1. is there any problem to handle data member which are created in the backgoundworker context from the main thread - for both reading and chaning valuse

  2. is there any design pattern for such issue? Idealy I'd like to run any delegate- any return value and a few genric parameters- as func built in delegate- that is problematic because It means if I want to 开发者_开发知识库support up to 3 parameters with or without return values I'll have to have 6 events and 6 listeners which actually do the same - does anyone have an idea of how to do this correct? Thanks!


I just wrote this for a similar question.

I use threads for these kind of stuff.

somewhere in my code:

// Definition 
private static Thread TH; 

....

// When process starts
TH = new Thread(new ThreadStart(Splash_MyCallBack)); 
TH.Start();

....

// This method starts the form that shows progress and other data
static private void Splash_MyCallBack()
{
   frmLoading FL;

   FL = new frmLoading();

   FL.ShowDialog();

} /* Splash_MyCallBack*/

// Your process calls Splash_Stop when it is done.
static public void Splash_Stop()
{
   TH.Abort();
} /* Splash_Stop*/

frmLoading performs the visual stuff, while in the background I have a very processor-intensive task. My process reports to an interface its progress. frmLoading implements that interface so it is aware of it and can show whaever it is needed (2 progress bars in my case) Tha only catch is, frmLoading must have this in the constructor:

Control.CheckForIllegalCrossThreadCalls= false;

which may be risky in some scenarios (not my case).

I think that the fact that the main process calls an interface to update progress, and the real interface consumes that is a pattern. Hope this helps, I can add more stuff if you like.

Regards,


To answer your first question:

There shouldn't be any problems handling data created in the background worker. I've done it in a couple of applications and not had any issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号