2017-05-29 37 views
0

私は、おそらくユーザーの認証を取得していること、this example on Micr*soft's blogRequestAccessAsyncを待つ方法

の手順は非常に2番目のコードスニップ以下、Windowsの通知にリスナーを作成しようとしていると言ってコンパイルされません:

error CS4033: The 'await' operator can only be used within an async method. 
Consider marking this method with the 'async' modifier and changing its return type to 'Task'. 

が、私はC#の非同期/待機メカニズムに精通していません。メソッドはRequestAccess と呼ばれ、非同期と呼ばれ、Visual Studioで開かれたソースにはメソッドの上に[RemoteAsync]があります。

これは完全なコードスニップです:

// Get the listener 
UserNotificationListener listener = UserNotificationListener.Current; 

// And request access to the user's notifications (must be called from UI thread) 
UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); 

switch (accessStatus) 
{ 
    // This means the user has granted access. 
    case UserNotificationListenerAccessStatus.Allowed: 

     // Yay! Proceed as normal 
     break; 

    // This means the user has denied access. 
    // Any further calls to RequestAccessAsync will instantly 
    // return Denied. The user must go to the Windows settings 
    // and manually allow access. 
    case UserNotificationListenerAccessStatus.Denied: 

     // Show UI explaining that listener features will not 
     // work until user allows access. 
     break; 

    // This means the user closed the prompt without 
    // selecting either allow or deny. Further calls to 
    // RequestAccessAsync will show the dialog again. 
    case UserNotificationListenerAccessStatus.Unspecified: 

     // Show UI that allows the user to bring up the prompt again 
     break; 
} 

どのように私はこの問題を解決することができますか?

+1

どこメソッドのシグネチャは?あなたは 'async'とマークしましたか? –

+1

コードをもっと表示する必要があります。コード例を保持するメソッドを表示する必要があります。 –

+0

問題のある人に感謝します。このコードは、コンストラクタで非同期コードを実行するための回避策についての私の更新された回答を参照してください(私が学んだように、非同期にすることはできません)クラスコンストラクタにあった – RSFalcon7

答えて

2

これは完全なコードスニペットではありません。呼び出し方法をasyncとマークする必要があります。コンストラクタでこれを行うには

public async Task<ReturnType> MyMethod() 
{ 
    // Get the listener 
    UserNotificationListener listener = UserNotificationListener.Current; 

    // And request access to the user's notifications (must be called from UI thread) 
    UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); 
} 

、あなたのコメントのとおり、私はこのようなNito.AsyncExAsyncContextを使用します。

public class MyProgram 
{ 
    public MyProgram() 
    { 
     UserNotificationListenerAccessStatus accessStatus = AsyncContext.Run(listener.RequestAccessAsync); 
    } 
} 
関連する問題