全局变量不会在回调函数上递增

时间:2010-01-24 14:35:58

标签: c# winforms webclient

我正在使用Webclient使用异步调用将数据上传到服务器,

    WebClient webClient = new WebClient();
   webClient.UploadDataAsync(uri , "PUT", buffer, userToken);

我已将DatauploadProgress和DatauploadCompleted事件附加到适当的回调函数

        // Upload Date Completed 
        webClient.UploadDataCompleted += new
                UploadDataCompletedEventHandler(UploadDataCallback2);

        // Upload Date Progress
        webClient.UploadProgressChanged += new 
                 UploadProgressChangedEventHandler(UploadProgressCallback);

在函数中我试图显示一些MessageBoxes:

      // Upload Date Progress
     void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
    {
        MessageBox.Show( this,"Upload Progress  ,x =" +x);
        x++;
        MessageBox.Show(e.BytesSent.ToString());
    }



        // Upload Date Completed 
     void UploadDataCallback2(object sender, UploadDataCompletedEventArgs e)
    {

        MessageBox.Show(this, "Upload Done,x =" +x);
        x++;
        MessageBox.Show(ASCIIEncoding.UTF8.GetString(e.Result));
    }

其中x是全局变量,但由于某种原因,x没有增加,所有消息框都显示x = 0 ..

任何解释都会非常感激..

1 个答案:

答案 0 :(得分:1)

哦发现了问题,显然这个问题是一个由两部分组成的问题,我希望有人能证实我的结论:

  • 关于进度的MessageBox.show,阻止函数进行,导致x保持为零直到我按下确定。
  • 我上传的文件太小,所以在我有足够的时间点击进度事件中消息框上的确定之前调用了datauploadcompleted事件