从异步任务访问datetime值时出现问题

时间:2014-07-14 22:31:31

标签: c# google-api google-api-dotnet-client

我正在尝试在Google日历上插入活动。一切正常,但唯一的问题是当我更改datetimepicker的值时,它在执行时不会改变。例如,如果我将datetimepicker的值更改为“2014-07-25”,它仍会在MessageBox上显示为当前日期。

这是我的代码:

private void btnsubmitevent_Click(object sender, EventArgs e)
{
    try
    {
        new frm_addeventcal().Run().Wait();
    }
    catch (AggregateException ex)
    {
        foreach (var exi in ex.InnerExceptions)
        {
            MessageBox.Show("ERROR: " + exi.Message);
        }

        MessageBox.Show(ex.InnerException.Message);
    }
}

private async Task Run()
{            
    UserCredential credential;
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "my cliend id",
            ClientSecret = "my secret key"
        },
        new[] { CalendarService.Scope.Calendar},
        "my gmail id",
        CancellationToken.None
    );

    var service = new CalendarService(new BaseClientService.Initializer() {
        HttpClientInitializer = credential,
        ApplicationName = "project name",
    });

    Event newevent = new Event();
    EventDateTime start = new EventDateTime();
    EventDateTime end = new EventDateTime();

    start.DateTimeRaw = dateTimePicker1.Value.ToString("yyyy-MM-dd") + "T" + dateTimePicker3.Value.ToString("HH:mm:ss");
    MessageBox.Show(start.DateTimeRaw); // here it shows current date although I changed the value of it.

    end.DateTimeRaw = dateTimePicker2.Value.ToString("yyyy-MM-dd") + "T" + dateTimePicker4.Value.ToString("HH:mm:ss");
    MessageBox.Show(end.DateTimeRaw); // same thing happens here too.

    newevent.Summary = "Hello World";
    newevent.Location = "my location";
    newevent.Description = "Random Description";
    newevent.Start = start;
    newevent.End = end;
    var calendarstry = service.Events.Insert(newevent, "calendar id").ExecuteAsync();
}

我是谷歌api和异步任务的新手。但我认为这个问题是因为我正在使用异步任务。

1 个答案:

答案 0 :(得分:2)

我认为您的问题是,您在创建表单时立即在Run上调用frm_addeventcal方法:

new frm_addeventcal().Run()...

这并没有让你有机会改变DateTimePickers的价值。在使用它们的值之前这是令人困惑的,因为你说你确实改变了这些值。

您应该像这样创建frm_addeventcal

var form = new frm_addeventcal();
form.ShowDialog();

然后您要等到日期时间设置为Run之前。我认为您希望在让用户更改日期值的同时显示表单,并且只有当用户点击提交时才会执行Run

public class frm_addeventcal : Form
{
    public frm_addeventcal() {
        InitializeComponent();
    }

    private async void btnSubmit_Click(object sender, EventArgs e) {
        await Run();
    }

    private async Task Run() {
        // the DateTimePickers' values should be correct here since this wont 
        // run until submit is clicked
    }
}