Câu hỏi phỏng vấn .NET Core
Câu hỏi

What is an unmanaged resource in .NET?

Câu trả lời

In .NET, an unmanaged resource refers to any resource that is not directly managed by the .NET runtime's garbage collector (GC). These resources typically include operating system resources such as file handles, network sockets, database connections, and memory allocated outside the .NET runtime. Unlike managed resources, which the GC can automatically clean up, unmanaged resources require explicit management by the developer to ensure they are properly released when no longer needed.

Key Points about Unmanaged Resources:

  1. Definition:

    • Unmanaged resources are those that the .NET garbage collector does not handle. Examples include file handles, network sockets, database connections, and other resources provided by the operating system[1][2][3][4].
  2. Management:

    • Since the GC does not manage these resources, developers must explicitly release them to avoid resource leaks. This is typically done using the IDisposable interface, which provides a Dispose method to clean up unmanaged resources[1][2][4][5].
  3. Examples:

    • File Handles: When working with file streams, the underlying file handle is an unmanaged resource.
    • Network Sockets: Network connections that are opened and maintained by the application.
    • Database Connections: Connections to a database that need to be explicitly closed to free up resources[1][2][4].
  4. Disposal Patterns:

    • IDisposable Interface: Implementing the IDisposable interface allows developers to provide a Dispose method that can be called to release unmanaged resources deterministically[1][2][4][5].
    • Using Statement: The using statement in C# ensures that the Dispose method is called automatically when the object goes out of scope, providing a convenient way to manage resource cleanup[1][2][4].
    • Finalizers: As a fallback, finalizers (or destructors) can be used to clean up unmanaged resources if Dispose is not called. However, finalizers are non-deterministic and should not be relied upon as the primary method for resource cleanup[1][2][5].

Example:

Here is an example of a class that manages an unmanaged resource (a file handle) using the IDisposable interface:

csharp Copy
public class FileProcessor : IDisposable
{
    private StreamReader _reader;
    private bool _disposed = false;

   ...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

What is the difference between IHost vs IHostBuilder vs
IHostedService ?

middle

Explain the difference between Managed and Unmanaged code in .NET?

middle

What are the benefits of Explicit Compilation (AOT)?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào