这是正确的编码吗? [英] Is this correct coding?

查看:80
本文介绍了这是正确的编码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下编码是否正确?如果是,如何在Windows应用程序中完成相同的操作?

Is the following coding is correct?If yes how the same can be done in windows application?

static void Main(string[] args)
        {

            ThreadStart job = new ThreadStart(ThreadJob);
            Thread thread = new Thread(job);
            thread.Start();

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Main thread: {0}", i);
                Thread.Sleep(1000);
            }
        }

        static void ThreadJob()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Other thread: {0}", i);
                Thread.Sleep(500);
            }
        }

推荐答案

好吧,这是正确的代码,并不是说它很有道理,但可能是有用的练习.

一个重要的改进:传递给线程构造函数的方法不必是静态的.该事实的文献报道很少,但是由于自动传递了参数"this",它允许使用更强大,更安全的线程编程方法,它将使线程可以完全访问声明类.这样,您可以避免由于需要进行类型转换而导致参数安全的线程启动不太安全.

最好的方法是在线程周围进行包装.请查看我过去的解决方案:如何将ref参数传递给线程 [ ^ ].

现在,Windows应用程序.您应该标记要使用的库,请参阅我的评论.就做吧.
我会解释这个问题.

您无法从非UI线程调用与UI相关的任何操作.相反,您需要使用System.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA
All right, this is correct code, not that it has a lot of sense, but could be a useful exercise.

One important improvement: the method passed to a thread constructor does not have to be static. This fact is poorly documented but it allows for much more powerful and safe approach to thread programming as the parameter "this" is automatically passed and it will give a thread a full access to the declaring class. This way, you can avoid parametrized thread start which is not so safe because of the need to do type cast.

The best way to use this is making a wrapper around your thread. Please see my past solution: How to pass ref parameter to the thread[^].

Now, Windows Applications. You should have tag the library you want to use, please see my comment. Just do it.
I''ll explain the issue.

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


是的,您的代码是正确的,但重要的一点是您希望从中获得的收益.下面是相同的C ++代码.

Yes, your code is correct but important point is what you want to acheive from it. below is the c++ code for the same.

void __cdecl ThreadJob(void*);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	// Windows inilization...
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
	unsigned long ulThr1;
	
	switch(iMsg)
	{
		
		case WM_CREATE:

			ulThr1 = _beginthread(ThreadJob,0,(void*)hWnd);
		break;

		
		case WM_PAINT:
			int i=0; 
			char str[2];

			hDc=BeginPaint(hWnd,&ps);
			for(i=0; i<5; i++)
			{
				sprintf(str,"Main Thread -> No = %d",i);
				TextOut(hDc,5,5*(i*2),str,strlen(str));
			}
			EndPaint(hWnd,&ps);
		break;

		// Other cases...

	}
	return DefWindowProc(hWnd,iMsg,wParam,lParam);
}

void __cdecl ThreadJob(void* param)
{
	HDC hDc;
	int j;
	char str[2];

	hDc = GetDC((HWND)param);

	for(j=0; j<10; j++)
	{
		sprintf(str,"Other Thread -> No = %d",j);
		TextOut(hDc,50,5*(j*2),str,strlen(str));
	}
	ReleaseDC((HWND)param,hDc);
	
}


这篇关于这是正确的编码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆