C# Top-level Statements WPF μ‹€ν–‰ 방법?

μ•ˆλ…•ν•˜μ„Έμš”. :smile:

C# 9.0 κΈ°λŠ₯인 Top-level Statements에 λŒ€ν•΄ μ•Œμ•„λ³΄κ³  μžˆλŠ”λ°μš”.

ν˜Ήμ‹œ WPF도 μ‹€ν–‰ν•  수 μžˆμ„κΉŒμš”?


Console의 κ²½μš°μ—λŠ” 잘 λ™μž‘ν•˜λŠ” 것을 ν™•μΈν–ˆμŠ΅λ‹ˆλ‹€.

using System;

Console.WriteLine("Hello");
Console.WriteLine(args);

κ·Έλž˜μ„œ 이와 λΉ„μŠ·ν•˜κ²Œ WPF도 μ‘μš©ν•΄λ³΄μ•˜μŠ΅λ‹ˆλ‹€.

using System;

Application app = new Application();
app.Startup += (s, e) => new Window().Show();
app.Run();

앱을 μ‹€ν–‰ν•˜λ©΄ [STAThread] κ΄€λ ¨ μ—λŸ¬κ°€ λ‚©λ‹ˆλ‹€.

λ§Žμ€ UI ꡬ성 μš”μ†Œμ—μ„œ 호좜 μŠ€λ ˆλ“œκ°€ ν•„μš”ν•˜λ―€λ‘œβ€¦


κ·Έλž˜μ„œ [STAThread]도 μΆ”κ°€ν•΄λ΄€μŠ΅λ‹ˆλ‹€.

using System;

[STAThread]
void WpfStart()
{
    Application app = new Application();
    app.Startup += (s, e) => new Window().Show();
    app.Run();
}
WpfStart();

μ΄λ ‡κ²Œλ„ ν•΄λ΄€μ§€λ§Œ λ™μΌν•œ μ—λŸ¬κ°€ λ°œμƒλ©λ‹ˆλ‹€.

ν˜Ήμ‹œ μ œκ°€ 잘λͺ» μ‚¬μš©ν•œ 뢀뢄이 μžˆμ„κΉŒμš”? 그리고 이 κΈ°λŠ₯이 μ–΄λ–€ μ˜λ„λ‘œ μ‚¬μš©λ˜μ•Ό ν•˜λŠ”μ§€λ„ κΆκΈˆν•©λ‹ˆλ‹€!

μ½μ–΄μ£Όμ…”μ„œ κ°μ‚¬ν•©λ‹ˆλ‹€.

μ’‹μ•„μš” 2

Top-level StatementsλŠ” attributeλ₯Ό μ“Έ 수 μ—†λŠ” κ²ƒμœΌλ‘œ ν™•μΈλ©λ‹ˆλ‹€. TLSλŠ” 처음 C# 을 μ ‘ν•˜λŠ” μ‚¬λžŒμ΄ μ–Έμ–΄λ₯Ό μ ‘κ·Όν•˜κΈ° μ‰½κ²Œ ν•˜κΈ° μœ„ν•œ λͺ©μ μ΄ μžˆμ–΄μ„œ κ·ΈλŸ°κ²ƒ κ°™μŠ΅λ‹ˆλ‹€.

μ’‹μ•„μš” 2

μ–΄μ©” 수 μ—†μŠ΅λ‹ˆλ‹€. 직접 ν•΄μ€˜μ•Όμ£ . ^^; μ•„λž˜μ˜ 글에 κ΄€λ ¨ 닡변이 μžˆμŠ΅λ‹ˆλ‹€.

[c# 9.0 - How to handle {STAThread] in C# 9 Using Top-Level Program.cs - Stack Overflow](c# 9.0 - How to handle {STAThread] in C# 9 Using Top-Level Program.cs - Stack Overflow)

ν˜Ήμ€ μ’€ 더 λ³΅μž‘ν•˜μ§€λ§Œ μ•„λž˜μ˜ 글에 μžˆλŠ” StartSTATask λ©”μ„œλ“œλ₯Ό μ΄μš©ν•΄,

c# - Set ApartmentState on a Task - Stack Overflow

λ‹€μŒκ³Ό 같은 μ‹μœΌλ‘œ μ½”λ”©ν•˜λ©΄ λ©λ‹ˆλ‹€.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

await StartSTATask(() =>
{
    Application app = new Application();
    app.Startup += (s, e) => new Window().Show();
    app.Run();

    return 0;
});

static Task<T> StartSTATask<T>(Func<T> func)
{
    var tcs = new TaskCompletionSource<T>();
    Thread thread = new Thread(() =>
    {
        try
        {
            tcs.SetResult(func());
        }
        catch (Exception e)
        {
            tcs.SetException(e);
        }
    });

    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return tcs.Task;
}
μ’‹μ•„μš” 4

λΉ„μŠ·ν•œ 이유둜 Windows Forms μ• ν”Œλ¦¬μΌ€μ΄μ…˜λ„ TLP κΈ°λŠ₯으둜 μ½”λ“œλ₯Ό μ‹œμž‘ν•  수 μ—†κ³ , μ•žμ˜ 뢄듀이 닡글을 달아주신 κ²ƒμ²˜λŸΌ workaroundλ₯Ό μž…ν˜€μ•Ό ν•˜λŠ”λ° β€œκ΅³μ΄?” 싢은 뢀뢄이 μƒκΈ°λŠ” 것 κ°™μ•„μš”. γ…Žγ…Ž

μ’‹μ•„μš” 2

μ•„, 그리고 이제 WPF에 κ΄€λ ¨λœ λ‚΄μš©μ€ μœˆλ„μš° λ°μŠ€ν¬ν†± Q&A μͺ½μœΌλ‘œ μ˜¬λ €μ£Όμ‹œλ©΄ 더 쒋을 것 κ°™μŠ΅λ‹ˆλ‹€! @james.lee

μ’‹μ•„μš” 2