Question

Application crashing in between, MFC, VC++

Asked by: rbhargaw

I have a Dialog box under the VC++ Client/Server (unmanaged code) application which contain two list box..One set of listbox1 data is filled from database and one set set of listbox2 from webservice...Both of them are called when I click on Search button after giving the necessary inputs in the dialog box ..The  functions used to populate from database are below
-------------------------------
PrepareForSearch();      
      DoSearch();
"DisplayResult();
-----------------------------------------
after that I am calling Web service call via create thread...

The issue is if I select the data in the listbox( which is already filled by database) without waiting for 5 seconds for the Web serivce call to finish..the code just hangs..

The webservice data normally comes back in 3-4 seconds so if on that period someone clicks on listbox1..the program crashes..

what would be ideal solution in the scenario?

void CDlgFinCoverageSearch::OnButSearch()
{
	
	
	CWaitCursor wc;
 
	PrepareForSearch();	
	DoSearch();
	DWORD dwTID;
	DisplayResult();
	m_nTimer = SetTimer(1,5000,NULL);
	
	m_hThread = CreateThread(NULL,0,WebServiceCallThread, (LPVOID) this,0,&dwTID);
	if(m_hThread == NULL)
	{
		DWORD dwError = GetLastError();
		AfxMessageBox( dwError);
		return;
	}
	//CloseHandle(hThread);
	//DisplayResult();
 
	GotoDlgCtrl(&m_lcList);
	m_bChange = FALSE;
 
	if(m_lcList.GetItemCount()) // something there
		MakeDefaultButton(OK);
}
 
------------------------------------------------------------------------------------------------------------------------
 
DWORD WINAPI CDlgFinCoverageSearch::WebServiceCallThread(LPVOID pv) 
{
	CDlgFinCoverageSearch* pWnd = (CDlgFinCoverageSearch*) pv;
	pWnd->VFSWEbServiceCall();
	pWnd->PostMessage(WM_WEBSERVICEDONE,0,0);
	return 1;
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-14 at 08:25:21ID24811573
Tags

MFC

,

VC++

Topics

Microsoft Programming

,

Windows MFC Programming

,

.NET

Participating Experts
3
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. VC++
    I programme in VB5, and I need to start to learn C++, I tried but I did not how even to start, please kindly some one start me up with the fisrt step to understand the logic og VC++ which I have for along time without use. Please simple steps so I can follow. thanks
  2. Version Of MFC in VC++ 6.0
    Which version of MFC is used in VC++ 6.0 Is it MFC ver4.0?
  3. again vc++
    sir, i have already asked this thing but now a bit deeper. Well the point is that i know vc++(api way in a very very good way). Now i have already started MFC and touchwood i am doing very very well in MFC. My actual problem is that i have this great obsession with...
  4. VC++.NET Compatible with VC++6.0 Projects?
    I am thinking about making the leap from VS 6.0 to .NET. But I have a vast set of legacy applications and libraries in the forms of VC++6.0 Projects. Will VC++.NET import .DSW/.DSP files to produced good old fashioned native .EXEs? (Neither I nor my customers are ready (yet...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: AndyAinscowPosted on 2009-10-14 at 08:32:36ID: 25571724

This might not be relevant.
MFC is not thread safe so
        CDlgFinCoverageSearch* pWnd = (CDlgFinCoverageSearch*) pv;
       pWnd->VFSWEbServiceCall();
       pWnd->PostMessage(WM_WEBSERVICEDONE,0,0);
is not especially good - it might crash or it might work without problems depending on luck.

It is better to pass the window handle (GetSafeHwnd()) and use ::PostMessage(hWndRecipient....) instead

 

by: rbhargawPosted on 2009-10-14 at 10:49:23ID: 25573106

I had an issue before ,where OnTimer () function was not working and I started using thread which is working fine
as of now
http://www.experts-exchange.com/Programming/System/Windows__Programming/MFC/Q_24616997.html

What will be your recommendations?

 

by: DanRollinsPosted on 2009-10-14 at 22:56:49ID: 25577640

I recommend avoiding the use of a secondary thread. See the article.

If you must use a thread (and you probably don't need to here) you must avoid accessing U/I elements such as list controls while in the secondary thread. You need to set up a convoluted sequence of posting messages (or other technique) so the main thread can handle that.

 

by: AndyAinscowPosted on 2009-10-14 at 23:20:40ID: 25577742

First I would just pass the window handle and see if that cures your problem.

 

by: AndyAinscowPosted on 2009-10-15 at 00:14:17ID: 25578003

I've just realised
pWnd->VFSWEbServiceCall();

That is probably the cause of your crash - I suspect you are trying to fill the listbox directly.  

If my guess is correct then you need to use a list (array, some other container) to fill with the items, then when the thread finishes the main app can fill the listbox from the intermediate collection.

 

by: rbhargawPosted on 2009-10-15 at 07:35:15ID: 25580931

yeah ..you are correct..I am filling the listbox directly in "pWnd->VFSWEbServiceCall()"...
This function contains creating request and response messages, calling stored procedures, populating listbox, SSL initialization,

 

by: AndyAinscowPosted on 2009-10-15 at 07:45:24ID: 25581075

Strip out the bits that add strings/values to the listbox and add them to a list in memory (not a window).  Then when it is done pass the list onto the main window and let that put the entries in there into the listbox.

 

by: rbhargawPosted on 2009-10-15 at 08:32:09ID: 25581615

Actually my problem of crash is different...but I understand that nothing should be UI related in the worker thread...

I will try to be clear..
I have two list boxes on a dialog..which gets called when I click on Button search...

1. List1 fills very quickly from database.
2. List2 takes time around 3-4 seconds..(Webservice)

Now problem is if I click on List1 data lets say in 1 seconds without even allowing List2 to get filled ...the application crashes..

since the dialog box has to close, and list2 data is not populated and windows didn't get the message that web service thread is complete..the application crash...

I don't know if this is possible or not, to get the flag across application...I tried but didn't work
bool  flag = pWnd->PostMessage(WM_WEBSERVICEDONE,0,0);

or May be it is only putting bandage on much bigger problem which can come in later time as referred in the tutorials provided by Dan...

Please let me know your views...


 

by: AndyAinscowPosted on 2009-10-15 at 08:56:24ID: 25581883

The problem is that MFC is not thread safe.  Directly accessing one MFC based window from a different thread (as you do) can result in crashes.  I don't know the precise details but some things are handled on a thread specific basis, accesing directly from another thread means the information that MFC uses for the window to work is incorrect.  

Just give this a quick try.  Comment out the two lines in your thread starting with pWnd-> and replace with some dummy code eg. sleep(5000) - see if your app still crashes.  


ps.  If you code a thread properly then it will work without problems (same as coding an app really - do something wrong and it can crash).

 

by: rbhargawPosted on 2009-10-15 at 09:48:39ID: 25582388

I commented this code and application does not crash..

//pWnd->VFSWEbServiceCall();

 

by: AndyAinscowPosted on 2009-10-15 at 09:59:21ID: 25582461

So the problem seems to be what I suggested it could be.

 

by: DanRollinsPosted on 2009-10-15 at 15:43:55ID: 25585625

>> Now problem is if I click on List1... the application crashes.

Indeed that is a common problem when secondary threads interact with the U/I in MFC (and actually most kinds of) programs. The specific reasons for the problem are hard to describe, but the symptoms are easy to recognize :-)

If you must use a secondary thread, then do as AndyAinscow suggested: Have it populate, say, a CStringArray or other in-memory array.  When it is done, have it set a flag that the U/I handler (your dialog) can see.  Then have a Window Timer check that flag and when the flag is set, populate the entire listbox from the CStringArray (and kill the timer).

 

by: itsmeandnobodyelsePosted on 2009-10-17 at 06:26:03ID: 25595875

>>>> I commented this code and application does not crash..
>>>> //pWnd->VFSWEbServiceCall();

In the pWnd->VFSWEbServiceCall(); instead of filling the listbox put the entries to a vector<CString>


 void MyCtrl::VFSWEbServiceCall()
 {
      // your code until filling of the listctrl
      ...
      // filling the listctrl
      std::vector<CString> * ptrArr = new std::vector<CString>;
      for (int i = 0; i < numEntriesOfListBox; ++i)
      {
           ptrArr->push_back(StringsToDisplayInListBox[i]);
      }
      // send message to dialog which is the parent of the listbox control
      GetParent(m_hWnd)->PostMessage(WM_FILL_MY_LISTBOX,
                                                                 (LPARAM)ptrArr,
                                                                 (WPARAM)numEntriesOfListBox);
 }

// yourdialog.cpp

BEGIN_MESSAGE_MAP(YourDialog, CDialog)
{
       // existing message handlers
       ....
       // message handler to fill the listbox from vector
       ON_MESSAGE(WM_FILL_MY_LISTBOX, OnFillListBox)
}


void YourDialog::OnFillListBox(LPARAM lp, WPARAM wp)
{
     m_lstBox.ResetContent();
     std::vector<CString> * ptrArr = (std::vector<CString> *)lp;
     for (int i; i < (int)ptrArr->size(); ++i)
     {
          m_lstBox.AddString((*ptrArr)[i]);  
     }
     delete ptrArr;
}

That way you would move the filling from worker thread to main thread.


 

by: rbhargawPosted on 2009-10-26 at 20:14:08ID: 25668883

I am trying to use CStringArray for filling the list control so I have 5 CStringarray for the five column values..

How do I pass the flag to dialog so that the listctrl gets filled on  OnFillListbox ?

I tried using GetParent()->PostMessage(WM_FILL_MY_LISTBOX,0,0); but it is not going into OnFillListBox
function
------------------------------------------------------------------------------------------------------------------
For (i =0;i < 3;i++)
{
arrProgram.Add();
arrProgram.Setat(i, name);

.......................
..........................

}
GetParent()->PostMessage(WM_FILL_MY_LISTBOX,0,0);
}

#define WM_FILL_MY_LISTBOX (WM_USER + 2)
 
BEGIN_MESSAGE_MAP(CDlgFinCoverageSearch, CPDialogSearch)
ON_MESSAGE(WM_FILL_MY_LISTBOX, OnFillListBox)
END MESSAGE
 
LRESULT CDlgFinCoverageSearch::OnFillListBox(WPARAM wParam, LPARAM lParam)
{
 
for  (i=0;i < size;i++
{
m_ListCtrl.AddItem(i, 0,arrProgram.GetAt(j), -1);
		m_ListCtrl.AddItem(i, 1,arrBankName.GetAt(j), -1);
		m_ListCtrl.AddItem(i, 2,arrPhonenum.GetAt(j), -1);
		m_ListCtrl.AddItem(i, 3,arrDescrip.GetAt(j), -1);
		m_ListCtrl.AddItem(i, 4,arrProduct.GetAt(j), -1);
 
		m_ListCtrl.SetItemData(i,j);
j++;
}
}
------------------------------------------------------------------------------------------
For (i =0;i < 3;i++)
{
 
if (eflag == true)
{
 
	arrProgram.Add(enhancement[i]->enhancementName);
	arrProgram.SetAt(j,enhancement[i]->enhancementName);
 
	}
else
{
 
	arrProgram.Add(str);
	arrProgram.SetAt(j,str);
}
 
arrBankName.Add(supplierName.Left(40));
arrBankName.SetAt(j,supplierName.Left(40));
 
if( !phone)
{
 
	arrPhonenum.Add("");
	arrPhonenum.SetAt(j,"");
}
else
{
 
	arrPhonenum.Add(phone[0]->phoneNumber);
	arrPhonenum.SetAt(j,phone[0]->phoneNumber);
}
 
 
arrDescrip.Add(typeName);
arrDescrip.SetAt(j,typeName);
 
arrProduct.Add(productName);
arrProduct.SetAt(j,productName );
}
 
GetParent()->PostMessage(WM_FILL_MY_LISTBOX,0,0);
			
			
			
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:

Select allOpen in new window

 

by: DanRollinsPosted on 2009-10-26 at 23:20:58ID: 25669486

It looks like you are doing it right... however there is one thing you could be getting wrong:

Are you sure that GetParent() will return the dialog that contains the message handler?

In the example, the source code beginning on line 23 is rather anonymous -- we can't tell what object it belongs to.   Since we have no information, it is impossible to say whether  GetParent() will return the CDlgFinCoverageSearch object.

 

by: AndyAinscowPosted on 2009-10-27 at 00:14:45ID: 25669722

<pre id="codeSnippet439369" class="prettyprint">if the folllowing line is in the thread function after the values have been retrieved from the web service
GetParent()->PostMessage(WM_FILL_MY_LISTBOX,0,0);


then it should be
PostMessage(hWndOwner, WM_FILL_MY_LISTBOX,0,0);
where hWndOwner is the HWND of the window you want to receive the message (namely
CDlgFinCoverageSearch
) which you passed into the thread as part of the parameters.</pre>

 

by: rbhargawPosted on 2009-11-06 at 07:42:01ID: 31641104

Thanks a lot for the detailed information!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...