STM32F7 discovery USB device CDC using CubeMX
I finally found the solution. The problem was related to the heap size. I increased the heap size in the startup file from 200 bytes to 400 bytes, so it's working like a charm. But still not the whole problem has been solved. when I use Keil rtx, it stops working. The previous  problem appears again. I believe it is about the stack size in rtx config, but with some changes, it's still not working.

Edited:
After a lot of challenge it worked out. In this link, it describes some tips about using RTOS-RTX with Stm32CubeMX. One of the things you need to do is setting the priority of SysTick timer in the lowest value. This conflicts with USB interrupts. To use USB-CDC with RTOS-RTX in Stm32CubeMX, you have to set the priority of USB-OTG global interrupt, lower than the SysTick timer. So setting SysTick priority to 14 and USB-OTG to 15 solves the problem.