There is a sentence:
While Mary was writing a letter, the children were playing outside.
Since “while” means “during the time”, can I replace “while” with “when”? If not, please explain.
Yes, you can replace while with when.
If there's a difference at all, it's a very minor one: while can connote a longer span of time, and the word when can refer to a single moment in time. Consider:
The first sentence points to a specific moment in time – that moment when the alarm went off. The second sentence refers to a longer span of time – it could be interpreted as: "I heard the alarm go off, and then I kept hearing the alarm go off while I stayed in the library."
So, if you wanted to emphasize how Mary was letter-writing and the children were playing over a certain span of time, while might be the better word to use.
In your example, the use of the progressive verb tense – that is, was writing instead of wrote – makes while the better word to use, in my opinion. But I wouldn't go so far as to say that when would be awkward or incorrect.
Like many subtle nuances of English, this one can get tricky:
This emphasizes how Mary was in the process of writing a letter, and she was interrupted by the phone ringing.
This says the same thing, but "when" points to the moment when the phone rang.
This emphasizes how the phone was ringing for some period of time.
J.R. has hit most of it, but there's another possible difference. "While" can be used to create a contrast.
This can sometimes mean that Mary is the studious, responsible one, taking care of her letter writing, while the children are frivolously playing. It's even more obvious in this example: "While I practiced my violin, my brother just watched television." I'm emphasizing the contrast between us, suggesting that I'm being responsible, and he's wasting time.
Using "when" in that sentence could not give it that implication.