none
How to make thread safe calls

    Question

  • Hello,

    I have this code:

    public delegate void CallBack(string szMessage, int nProgress);
    private CallBack callBack;
    
    [DllImport("BX_IV.dll")]
    public static extern int Initialize(IntPtr DllApp, CallBack pCallBack);
    
    private void CallBackMethod(string szMessage, int nProgress)
    {
        TxtBoxThreadSafeMessage("status: " + szMessage);//method to invoke a textBox from another thread
    } 
    public void GetErrorMessage(string szfunctionName, int nResult)
    {
    	string szResult;
    	DateTime dt = DateTime.Now;
    	szResult = dt.ToString() + "Executive function: " + szfunctionName + "Returns the result:";
    	switch (nResult)
    	{
    	case 0x01:
    		txtStatus.Text += szResult + "Communication error\r\n";
    		break;
    	case RETURN_ERROR_NOW_SENDING:
    		txtStatus.Text += szResult + "It’s communicating now, please try again later.\r\n";
    		break;
    	}
    }
    main()
    {
    	callBack = new CallBack(CallBackMethod);
    	int nResult = Initialize(this.Handle, callBack);
    	GetErrorMessage("Initialize", nResult);
    }



    When calling this Initialize method, my GUI freezes for about one minute. How can I do this thread safe in a background?

    Similar question is here:

    http://stackoverflow.com/questions/40254391/backgroundworker-wont-execute-extern-dll-function-in-dowork-method

    • Edited by bobis123 Wednesday, April 26, 2017 7:37 AM
    Wednesday, April 26, 2017 7:14 AM

Answers

  • I have invoke it like this.

        Invoke((MethodInvoker)delegate
        {
            int nResult = Initialize(this.Handle, callBack);
            GetErrorMessage("Initialize", nResult);
        });


    • Marked as answer by bobis123 Friday, May 5, 2017 6:33 AM
    Friday, May 5, 2017 6:33 AM